用scrapy蜘蛛刮蟒蛇网

时间:2015-01-21 15:33:50

标签: python string web-scraping scrapy

我正在使用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")

在“内容”中我有抓取的信息。

我有:

  1. 使用字符串比较
  2. 必须创建查找文件并进行匹配
  3. 但我想知道他们有效地做到这一点吗?

1 个答案:

答案 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}}。一个好主意是在项目设置中配置它。

此外,如果您要跳过包含任何已定义术语的项目,请考虑将检查移至蜘蛛级别。这有助于避免将项目从蜘蛛传递到管道的开销。

相关问题