I was trying to set default value when the result of my xpath selector return None. This happens when in some pages the xpath node dont exist and I want to set for example 'N/A' or 'Not found'.
I used the following code but I think this isn't clean and efficient:
value = response.xpath(property.xpath).extract_first()
if(value != None):
data[property.name] = response.xpath(property.xpath).extract_first()
else:
data[property.name] = "N/A"
Any ideas? Thanks
There is no need to do the query twice, a simple solution is to pass a default value:
data[property.name] = response.xpath(property.xpath).extract_first(default='N/A')
For future reference, if you were to rewrite your own code without using the default keyword, I would query once and use an if/else:
value = response.xpath(property.xpath).extract_first()
data[property.name] = value if value else "N/A"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With