【发布时间】:2016-02-04 13:05:00
【问题描述】:
我正在尝试学习 python 和 scrapy,但我在使用 CrawlSpider 时遇到了问题。
下面的代码对我有用。它获取起始 url 中与 xpath 匹配的所有链接 - //div[@class="info"]/h3/a/@href 然后将这些链接传递给函数 parse_dir_contents。
我现在需要的是让爬虫移动到下一页。我尝试使用规则和链接提取器,但似乎无法使其正常工作。我还尝试使用//a/@href 作为 parse 函数的 xpath,但它不会将链接传递给 parse_dir_contents 函数。我想我错过了一些非常简单的东西。有什么想法吗?
class ypSpider(CrawlSpider):
name = "ypTest"
download_delay = 2
allowed_domains = ["yellowpages.com"]
start_urls = ["http://www.yellowpages.com/new-york-ny/restaurants?page=1"]
rules = [
Rule(LinkExtractor(allow=['restaurants?page=[1-2]']), callback="parse")
]
def parse(self, response):
for href in response.xpath('//div[@class="info"]/h3/a/@href'):
url = response.urljoin(href.extract())
if 'mip' in url:
yield scrapy.Request(url, callback=self.parse_dir_contents)
def parse_dir_contents(self, response):
for sel in response.xpath('//div[@id="mip"]'):
item = ypItem()
item['url'] = response.url
item['business'] = sel.xpath('//div/div/h1/text()').extract()
---extra items here---
yield item
编辑: 这是具有三个功能的更新代码,能够抓取 150 个项目。我认为这是我的规则有问题,但我尝试了我认为可行的方法,但输出仍然相同。
class ypSpider(CrawlSpider):
name = "ypTest"
download_delay = 2
allowed_domains = ["yellowpages.com"]
start_urls = ["http://www.yellowpages.com/new-york-ny/restaurants?page=1"]
rules = [
Rule(LinkExtractor(allow=[r'restaurants\?page\=[1-2]']), callback='parse')
]
def parse(self, response):
for href in response.xpath('//a/@href'):
url = response.urljoin(href.extract())
if 'restaurants?page=' in url:
yield scrapy.Request(url, callback=self.parse_links)
def parse_links(self, response):
for href in response.xpath('//div[@class="info"]/h3/a/@href'):
url = response.urljoin(href.extract())
if 'mip' in url:
yield scrapy.Request(url, callback=self.parse_page)
def parse_page(self, response):
for sel in response.xpath('//div[@id="mip"]'):
item = ypItem()
item['url'] = response.url
item['business'] = sel.xpath('//div/div/h1/text()').extract()
item['phone'] = sel.xpath('//div/div/section/div/div[2]/p[3]/text()').extract()
item['street'] = sel.xpath('//div/div/section/div/div[2]/p[1]/text()').re(r'(.+)\,')
item['city'] = sel.xpath('//div/div/section/div/div[2]/p[2]/text()').re(r'(.+)\,')
item['state'] = sel.xpath('//div/div/section/div/div[2]/p[2]/text()').re(r'\,\s(.+)\s\d')
item['zip'] = sel.xpath('//div/div/section/div/div[2]/p[2]/text()').re(r'(\d+)')
item['category'] = sel.xpath('//dd[@class="categories"]/span/a/text()').extract()
yield item
【问题讨论】:
标签: python xpath scrapy web-crawler