【问题标题】:Scrapy needs to crawl all the next links on website and move on to the next pageScrapy 需要爬取网站上所有的下一个链接并进入下一页
【发布时间】:2015-01-23 03:18:18
【问题描述】:

我需要我的scrapy才能进入下一页,请给我正确的规则代码,如何编写?

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

from delh.items import DelhItem

class criticspider(CrawlSpider):
    name ="delh"
    allowed_domains =["consumercomplaints.in"]
    #start_urls =["http://www.consumercomplaints.in/?search=delhivery&page=2","http://www.consumercomplaints.in/?search=delhivery&page=3","http://www.consumercomplaints.in/?search=delhivery&page=4","http://www.consumercomplaints.in/?search=delhivery&page=5","http://www.consumercomplaints.in/?search=delhivery&page=6","http://www.consumercomplaints.in/?search=delhivery&page=7","http://www.consumercomplaints.in/?search=delhivery&page=8","http://www.consumercomplaints.in/?search=delhivery&page=9","http://www.consumercomplaints.in/?search=delhivery&page=10","http://www.consumercomplaints.in/?search=delhivery&page=11"]
    start_urls=["http://www.consumercomplaints.in/?search=delhivery"]
    rules = (Rule(SgmlLinkExtractor(restrict_xpaths=('//div[@class="pagelinks"]/a/@href',)),           
              callback="parse_gen", follow= True),
    )
    def parse_gen(self,response):
        hxs = Selector(response)
        sites = hxs.select('//table[@width="100%"]')
        items = []

        for site in sites:
            item = DelhItem()
            item['title'] = site.select('.//td[@class="complaint"]/a/span/text()').extract()
            item['content'] = site.select('.//td[@class="compl-text"]/div/text()').extract()
            items.append(item)
        return items
spider=criticspider()

【问题讨论】:

    标签: python web-scraping scrapy web-crawler scrapy-spider


    【解决方案1】:

    据我了解,您正在尝试抓取两种页面,因此您应该使用两个不同的规则:

    • 分页列表页面,包含指向 n 个项目页面和后续列表页面的链接
    • 项目页面,您可以从中抓取项目

    你的规则应该看起来像这样:

    rules = (
        Rule(LinkExtractor(restrict_xpaths='{{ item selector }}'), callback='parse_gen'),
        Rule(LinkExtractor(restrict_xpaths='//div[@class="pagelinks"]/a[contains(text(), "Next")]/@href')),
    )
    

    解释:

    • 第一条规则匹配项目链接并使用您的项目解析方法 (parse_gen) 作为回调。生成的响应不会再次通过这些规则。
    • 第二条规则匹配“pagelinks”并且没有指定回调,结果响应然后由这些规则处理。

    注意:

    • SgmlLinkExtractor 已过时,您应该使用 LxmlLinkExtractor(或其别名 LinkExtractor)代替 (source)
    • 您发送请求的顺序确实很重要,在这种情况下(抓取未知的、可能大量的页面/项目),您应该设法减少在任何给定条件下处理的页面数量时间。为此,我以两种方式修改了您的代码:
      • 请求下一个之前从当前列表页面中抓取项目,这就是项目规则位于“pagelinks”规则之前的原因。
      • 避免多次爬取页面,这就是我将[contains(text(), "Next")] 选择器添加到“页面链接”规则的原因。这样每个“列表页面”都会被请求一次

    【讨论】:

    • @ason​​ 抱歉回复晚了,我会在我的机器上运行这个,我会告诉你的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多