python - Scrapy - 理解 CrawlSpider 和 LinkExtractor

标签 python scrapy web-crawler scrapy-spider

所以我正在尝试使用 CrawlSpider 并理解 Scrapy Docs 中的以下示例:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

rules = (
    # Extract links matching 'category.php' (but not matching 'subsection.php')
    # and follow links from them (since no callback means follow=True by default).
    Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),

    # Extract links matching 'item.php' and parse them with the spider's method parse_item
    Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
)

def parse_item(self, response):
    self.logger.info('Hi, this is an item page! %s', response.url)
    item = scrapy.Item()
    item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
    item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
    item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
    return item

然后给出的描述是:

This spider would start crawling example.com’s home page, collecting category links, and item links, parsing the latter with the parse_item method. For each item response, some data will be extracted from the HTML using XPath, and an Item will be filled with it.

据我了解,对于第二条规则,它从 item.php 中提取链接,然后使用 parse_item 方法提取信息。但是,第一条规则的目的到底是什么?它只是说它“收集”了链接。这是什么意思,如果他们不从中提取任何数据,为什么有用?

最佳答案

CrawlSpider 在爬取论坛搜索帖子时非常有用,或者在搜索产品页面时对在线商店进行分类。

这个想法是,您必须“以某种方式”进入每个类别,搜索与您要提取的产品/项目信息相对应的链接。这些产品链接是该示例的第二条规则中指定的链接(它表示在 url 中具有 item.php 的链接)。

现在蜘蛛应该如何继续访问链接,直到找到包含 item.php 的链接?这是第一条规则。它说要访问每个包含 category.php 但不包含 subsection.php 的链接,这意味着它不会从这些链接中完全提取任何“项目”,但它定义了蜘蛛寻找真实元素的路径。

这就是为什么您会看到它在规则中不包含 callback 方法的原因,因为它不会返回该链接响应供您处理,因为它将被直接跟进。

关于python - Scrapy - 理解 CrawlSpider 和 LinkExtractor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44527996/

相关文章:

python - xpath如何获取<a>的最后一个元素之前

python - CSS Selector 获取元素属性值

javascript - 是否存在一种让爬虫忽略部分文档的方法?

javascript - 使用 scrapy python 从 javascript 获取数据到 python

algorithm - 网络爬虫算法 : depth?

python - 二维 numpy 数组的上对角线

python - 使用 scrapy-splash 点击按钮

javascript - 想要使用 Scrapy 抓取网站,但不确定是否有绕过 javascript 的方法

python - 如何将可迭代列表传递给 Python 中的 lambda 函数?

python - 如何在 Python 中绘制多面体和 Lemke-Howson 路径?