Write a little helper function:
def extractor(xpathselector, selector):
"""
Helper function that extract info from xpathselector object
using the selector constrains.
"""
val = xpathselector.select(selector).extract()
return val[0] if val else None
And use it like this:
citem['name'] = extractor(cotacao, "td[4]/text()")
Return an appropriate value to indicate that a citem
wasn't found. In my code I returned None
, change it if necessary (for example, return ''
if it makes sense).