我正在使用scrapy编写简单的蜘蛛,其中我想添加一些机制来找出我正在爬行的内容。
比如说我有字符串列表:
The resource you are looking for has expired
The resource is not available
就像我有成千上万的字符串。现在我想检查已爬网内容是否包含此内容。我怎么能做这个python?
def process_item(self, item, spider):
try:
content = items['body']
----------------------------- // How can i proceed further.
except pymssql.Error, e:
print ("error")
在“内容”中我有抓取的信息。
我有:
但我想知道他们有效地做到这一点吗?
答案 0 :(得分:1)
定义要检查的字符串列表,并使用内置的any()
函数:
terms = [
'The resource you are looking for has expired',
'The resource is not available'
]
has_terms = any(term in content for term in terms)
请注意terms
列表应在process_item()
之外定义,以避免每次调用process_item()
时重新定义{{1}}。一个好主意是在项目设置中配置它。
此外,如果您要跳过包含任何已定义术语的项目,请考虑将检查移至蜘蛛级别。这有助于避免将项目从蜘蛛传递到管道的开销。