我的列表中有两个项目存在或不存在。如何写清单检查?
项目看起来像这样
item['BusinessType'] = response.xpath('//div//following-sibling::p//text()').extract()[3]
item['BusinessArea'] = response.xpath('//div//following-sibling::p//text()').extract()[4]
有时列表成员[3]或[4]不存在,因此Scrapy失败了
IndexError: list index out of range
我尝试了几种不同的方法,但都失败了。我不懂为什么。将response.xpath指定为局部变量并使用
if biz_type:
item['BusinessType'] = biz_type
else:
biz_type_none = "None"
item['BusinessType'] = biz_type_none
if biz_area:
item['BusinessArea'] = biz_area
else:
biz_area_none = "None"
item['BusinessArea'] = biz_area_none
失败。 Scrapy抱怨名单仍然超出范围。
如何在列表提取过程中进行正确的检查?
编辑:下面的全部功能。这是'链'中的最后一个功能。它在之前的步骤中访问3页并使用meta传递项目。
def trust_data(self, response):
item = response.meta['item']
item ['Access'] = response.xpath('//div//following-sibling::p//text()').extract()[1]
item ['Feedback'] = response.xpath('//div//following-sibling::p//text()').extract()[2]
texts = response.xpath('//div//following-sibling::p//text()').get()
if len(texts) >= 4:
item['BusinessType'] = texts[3]
if len(texts) >= 5:
item['BusinessArea'] = texts[4]
yield item
另一件事,
print(texts, 'lenght is', len(texts))
(u'5600', 'lenght is', 4)
长度== 4,列表已完成
>>> print(texts, 'lenght is', len(texts))
(u'0', 'lenght is', 1)
长度== 1,列表不完整(它没有我希望包含在我的项目中的标签)
但条件
if len(texts) == 1
总是很满意,接下来我想做的任何事都将完成。例:
if len(texts) == 4:
if len(texts) >= 4:
item['BusinessType'] = texts[3]
if len(texts) >= 5:
item['BusinessArea'] = texts[4]
else:
item['BusinessType'] = "None"
item['BusinessArea'] = "None"
在所有可能的情况下,这两个项目都填充“无”。
在访问索引之前,请确保相应的列表足够长:
texts = response.xpath('//div//following-sibling::p//text()').getall()
item['BusinessType'] = texts[3] if len(texts) >= 4 else 'None'
item['BusinessArea'] = texts[4] if len(texts) >= 5 else 'None'