Deo*_*eia 4 python xpath scrapy web-scraping
当我的xpath选择器的结果返回None时,我试图设置默认值.当在某些页面中xpath节点不存在并且我想设置例如'N/A'或'Not found'时会发生这种情况.
我使用了以下代码,但我认为这不是干净而有效的:
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"
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢
Pad*_*ham 11
无需执行两次查询,一个简单的解决方案是传递默认值:
data[property.name] = response.xpath(property.xpath).extract_first(default='N/A')
Run Code Online (Sandbox Code Playgroud)
为了将来参考,如果你在不使用default关键字的情况下重写自己的代码,我会查询一次并使用if/else:
value = response.xpath(property.xpath).extract_first()
data[property.name] = value if value else "N/A"
Run Code Online (Sandbox Code Playgroud)