【发布时间】:2014-08-23 07:50:07
【问题描述】:
我无法理解如何在我自己的从 CrawlSpider 继承的 Spider 中使用规则字段。我的蜘蛛正在尝试在黄页中搜索旧金山的比萨饼列表。
我试图让我的规则保持简单,只是为了看看蜘蛛是否会爬过响应中的任何链接,但我没有看到它发生。我唯一的结果是它产生了对下一页的请求,然后产生了对后续页面的请求。
我有两个问题: 1. 蜘蛛收到响应后是否先处理规则再调用回调?或相反亦然? 2. 什么时候应用这些规则?
编辑: 我想到了。我覆盖了 CrawlSpider 的 parse 方法。在查看了该类中的 parse 方法后,我意识到这就是它检查规则并爬取这些网站的地方。
注意:了解您要覆盖的内容
这是我的代码:
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)
【问题讨论】:
-
是的,这是处理规则的默认
parse()方法。这是一个常见的混淆源,甚至有一个关于它的问题的报告,所以它可能会在下一个版本中得到解决。
标签: python scrapy rules web-crawler