链接类名的Scrapy回调条件



我是scrapy的新手,我正在尝试构建一个根据标签的类名解析响应的爬虫。我在文档中看到,您可以使用Rule()根据URL的allow和deny来定义回调函数,但这对我来说不起作用。真正起作用的是,如果一个标签有一个特定的类名(比如"item"),它应该去回调parse_item()。

我想要实现的是,我的爬虫访问所有网站链接从一个基础URL,并根据标签的类名,它应该存储该数据。

所以说:

  • 基础URL = example.com
  • 在这个基础URL上有两个链接:和
  • 爬虫应该访问这两个url并查找其中的其他链接,但只针对带有class="item"的链接。我想实际存储该页面的HTML。

LinkExtractor()有一个process_values()函数,用于处理attr()的值。但我不知道该怎么做。我尝试了以下方法:

class NewSpider(CrawlSpider):
name = 'newspider'
start_urls = ['https://example.com']
allowed_domains = ['example.com']
rules = (
Rule(LinkExtractor(attrs=('class',), process_value=(lambda x: True if (x == 'class_name') else False)), callback="parse_items"),)
)
def parse_items(self, response):
# store data

如果你想回调parse_xxx如果标签是xxx,你应该传递一个参数给默认的解析方法来定义回调函数,我以前写过一个蜘蛛来解析多域在一个蜘蛛。例如:

def google(response):
title = response.xpath('//title/text()')
yield title
Class TestSpider(spiders.Spider):
def start_requests(self):
yield Request(url='https://www.google.com', cb_kwargs={'parse_func':google})
def parse(self, response, parse_func):
parse_result = parse_func(response):
for item in pares_result:
yield item

最新更新