gpt4 book ai didi

python - 我如何减少这里的 try/catch 语句的数量?

转载 作者:太空宇宙 更新时间:2023-11-04 07:39:46 25 4
gpt4 key购买 nike

我目前正在使用 Scrapy 从网站上提取公司信息。但是,跨页面提供的数据量大不相同;例如,一家公司列出了其团队的三名成员,而另一家公司只列出了两名,或者一家公司列出了其所在地,而另一家则没有。因此,某些 XPath 可能会返回 null,因此尝试访问它们会导致错误:

try: 
item['industry'] = hxs.xpath('//*[@id="overview"]/div[2]/div[2]/p/text()[2]').extract()[0]
except IndexError:
item['industry'] = "None provided"
try:
item['URL'] = hxs.xpath('//*[@id="ContentPlaceHolder_lnkWebsite"]/text()').extract()[0]
except IndexError:
item['URL'] = "None provided"
try:
item['desc'] = hxs.xpath('//*[@id="overview"]/div[2]/div[4]/p/text()[1]').extract()[0]
except IndexError:
item['desc'] = "None provided"
try:
item['founded'] = hxs.xpath('//*[@id="ContentPlaceHolder_updSummary"]/div/div[2]/table/tbody/tr/td[1]/text()').extract()[0]
except IndexError:
item['founded'] = "None provided"

我的代码使用了很多 try/catch 语句。由于每个异常都特定于我要填充的字段,是否有更简洁的方法来解决这个问题?

最佳答案

使用TakeFirst() output processor :

Returns the first non-null/non-empty value from the values received, so it’s typically used as an output processor to single-valued fields.

from scrapy.contrib.loader.processor import TakeFirst

class MyItem(Item):
industry = Field(output_processor=TakeFirst())
...

然后,在蜘蛛内部,您根本不需要 try/catch:

item['industry'] = hxs.xpath('//*[@id="overview"]/div[2]/div[2]/p/text()[2]').extract()

关于python - 我如何减少这里的 try/catch 语句的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24657842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com