了解Scrapy的CrawlSpider规则

时间:2014-08-23 07:50:08

标签: python scrapy rules web-crawler

我无法理解如何在我自己的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)

1 个答案:

答案 0 :(得分:1)


所以说到你的两个问题......

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

  2. 在请求发出之前,再次使用爬网程序规则。

  3. 注意!

    在你的例子中,当你调用parse()方法时...虽然在你的情况下你正确使用它??!除非你在CRAWL蜘蛛中明确覆盖parse()方法,否则必须运行它来确认,但是当你使用爬行蜘蛛时... ...蜘蛛中的削减与爬虫的等价物是parse_item()。 ..爬虫中的parse()是一个自己的逻辑函数...在RULESET中使用作为回调不应该完成

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