【问题标题】:How can i jump to next page in Scrapy Rules如何在 Scrapy 规则中跳转到下一页
【发布时间】:2014-02-01 11:41:25
【问题描述】:

我设置了从 start_url 获取下一页的规则,但它不起作用,它只抓取 start_urls 页面和该页面中的链接(使用 parseLinks)。它不会转到规则中设置的下一页。

有什么帮助吗?

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from scrapy import log
from urlparse import urlparse
from urlparse import urljoin
from scrapy.http import Request

class MySpider(CrawlSpider):
    name = 'testes2'
    allowed_domains = ['example.com']
    start_urls = [
    'http://www.example.com/pesquisa/filtro/?tipo=0&local=0'
]

rules = (Rule(SgmlLinkExtractor(restrict_xpaths=('//a[@id="seguinte"]/@href')), follow=True),)

def parse(self, response):
     sel = Selector(response)
     urls = sel.xpath('//div[@id="btReserve"]/../@href').extract()
     for url in urls:
        url = urljoin(response.url, url)
        self.log('URLS: %s' % url)
        yield Request(url, callback = self.parseLinks)

def parseLinks(self, response):
    sel = Selector(response)
    titulo = sel.xpath('h1/text()').extract()
    morada = sel.xpath('//div[@class="MORADA"]/text()').extract()
    email = sel.xpath('//a[@class="sendMail"][1]/text()')[0].extract()
    url = sel.xpath('//div[@class="contentContacto sendUrl"]/a/text()').extract()
    telefone = sel.xpath('//div[@class="telefone"]/div[@class="contentContacto"]/text()').extract()
    fax = sel.xpath('//div[@class="fax"]/div[@class="contentContacto"]/text()').extract()
    descricao = sel.xpath('//div[@id="tbDescricao"]/p/text()').extract()
    gps = sel.xpath('//td[@class="sendGps"]/@style').extract()

    print titulo, email, morada

【问题讨论】:

标签: python web-scraping web-crawler scrapy


【解决方案1】:

您不应从CrawlSpider 覆盖parse 方法,否则将不会遵循Rules。

查看http://doc.scrapy.org/en/latest/topics/spiders.html#crawling-rules的警告

在编写爬虫规则时,避免使用 parse 作为回调,因为 CrawlSpider 使用 parse 方法本身来实现其逻辑。所以如果你重写 parse 方法,爬虫将不再工作。

【讨论】:

  • 我已将 parse 更改为 parsePage,并将 Rule 回调设置为 callback='parsePage' 并知道它不会进入 def parsePage
  • 尝试使用restrict_xpaths=('//a[@id="seguinte"]')), callback='parsePage', follow=True),)
【解决方案2】:

您正在使用 Spider 类流程:

class MySpider(CrawlSpider): is not the proper class
    instead of this use : class MySpider(Spider)
name = 'testes2'
allowed_domains = ['example.com']
start_urls = [
'http://www.example.com/pesquisa/filtro/?tipo=0&local=0'
]

In Spider Class you do not need rules. So discard it.
"Not Usable in Spider Class" rules = (Rule(SgmlLinkExtractor(restrict_xpaths=('//a[@id="seguinte"]/@href')), follow=True),)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多