了解Scrapy的CrawlSpider规则

OfL*_*ers 7 python rules web-crawler scrapy

我无法理解如何在我自己的Spider中使用继承自CrawlSpider的规则字段.我的蜘蛛正试图爬过旧金山披萨的黄页列表.

我试图保持我的规则简单只是为了看看蜘蛛是否会爬过响应中的任何链接,但我不认为它发生了.我唯一的结果是它产生了下一页的请求,然后产生对后续页面的请求.

我有两个问题: 1.在收到响应时,蜘蛛在调用回调之前是否先处理规则?或相反亦然? 2.什么时候适用规则?

编辑: 我明白了.我从CrawlSpider覆盖了解析方法.在查看该类中的解析方法后,我意识到这是检查规则并通过这些网站进行爬网的地方.

注意:知道你要覆盖的是什么

这是我的代码:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy import Selector
from yellowPages.items import YellowpagesItem
from scrapy.http import Request

class YellowPageSpider(CrawlSpider):
    name = "yellowpages"
    allowed_domains = ['www.yellowpages.com']
    businesses = []

    # start with one page
    start_urls = ['http://www.yellowpages.com/san-francisco-ca/pizza?g=san%20francisco%2C%20ca&q=pizza']

    rules = (Rule (SgmlLinkExtractor()
    , callback="parse_items", follow= True),
    )

    base_url = 'http://www.yellowpages.com'

    def parse(self, response):
        yield Request(response.url, callback=self.parse_business_listings_page)

    def parse_items(self, response):
        print "PARSE ITEMS. Visiting %s" % response.url
        return []

    def parse_business_listings_page(self, response):
        print "Visiting %s" % response.url

        self.businesses.append(self.extract_businesses_from_response(response))
        hxs = Selector(response)
        li_tags = hxs.xpath('//*[@id="main-content"]/div[4]/div[5]/ul/li')
        next_exist = False

        # Check to see if there's a "Next". If there is, store the links.
        # If not, return. 
        # This requires a linear search through the list of li_tags. Is there a faster way?
        for li in li_tags:
            li_text = li.xpath('.//a/text()').extract()
            li_data_page = li.xpath('.//a/@data-page').extract()
            # Note: sometimes li_text is an empty list so check to see if it is nonempty first
            if (li_text and li_text[0] == 'Next'):
                next_exist = True
                next_page_num = li_data_page[0]
                url = 'http://www.yellowpages.com/san-francisco-ca/pizza?g=san%20francisco%2C%20ca&q=pizza&page='+next_page_num
                yield Request(url, callback=self.parse_business_listings_page)
Run Code Online (Sandbox Code Playgroud)

scr*_*tso 2


所以就你的两个问题来说..

  1. 在发出请求之前,爬虫规则会在发出请求之前进行处理......当然,如果响应不符合允许的域,理论上会收到响应,但只是被丢弃。

  2. 同样,爬虫规则是在发出请求之前使用的。

笔记!

在您的示例中,当您调用 parse() 方法时...尽管在您的情况下您使用它是正确的??!必须运行它来确认,但是那些正在阅读的人,除非您在 CRAWL 蜘蛛中显式重写 parse() 方法...当使用爬行蜘蛛时...蜘蛛中的 pare 与爬虫的等效项是 parse_item()。 .. 爬虫中的 parse() 是它自己的逻辑函数...不应在规则集中使用作为回调

https://doc.scrapy.org/en/latest/topics/spiders.html