【问题标题】:Scrapy: follow pagination links not workingScrapy:跟随分页链接不起作用
【发布时间】:2017-09-15 12:10:23
【问题描述】:

设置

我正在使用here 给出的 scrapy 示例抓取房屋广告。

在我的例子中,我使用指向住房广告页面的链接而不是作者页面,随后废弃住房广告页面以获取信息。


问题

我的代码成功地跟踪到住房广告页面的链接,并抓取每个广告的信息。但是,它只对初始页面这样做,即它不遵循分页链接。


到目前为止的代码
class RoomsSpider(scrapy.Spider):
    name = 'rooms'

    start_urls = ['https://www.spareroom.co.uk/flatshare/london']

    def parse(self, response):
        # follow links to ad pages
        for href in response.xpath(
            '//*[@id="maincontent"]/ul/li/article/header[1]',
            ).css('a::attr(href)').extract():
            yield scrapy.Request(response.urljoin(href),
                             callback=self.parse_ad)

        # follow pagination links 
        next_page = response.xpath(
            '//*[@id="maincontent"]/div[2]/ul[2]/li/strong/a/@href',
            ).extract()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)      

     def parse_ad(self, response):
     # code extracting ad information follows here, 
     # finalising the code with a yield function.  

所以,我基本上是按照这个例子来的。我在运行代码时没有收到关于分页链接部分的错误,并且查询路径是正确的(我相信)。

我是否在代码中正确放置了# follow pagination links 部分?我迷路了。

【问题讨论】:

  • 你在scrapy shell中测试过response.xpath('//*[@id="maincontent"]/div[2]/ul[2]/li/strong/a',).css('a::attr(href)').extract()吗?我怀疑这不起作用,因为将 XPath 的 ...../a 选定元素与 CSS a 后代链接永远不会匹配(链接没有链接子项)。如果您真的想使用 XPath 和 CSS,请尝试 XPath /*[@id="maincontent"]/div[2]/ul[2]/li/strong/a/@href/*[@id="maincontent"]/div[2]/ul[2]/li/strong 后跟 CSS a::attr(href)
  • @paultrmbrth, response.xpath('//*[@id="maincontent"]/div[2]/ul[2]/li/stron‌​g/a',).css('a::attr(‌​href)').extract() 在 Scrapy shell 中工作。也就是说,它为我提供了“下一个”href。
  • 我已将其更改为response.xpath('//[@id="maincontent"]/div[2]/ul[2]/li/strong/a/@href').extract(),它提供了href。我会在问题中更改它。
  • @paultrmbrth。我发现了问题,href 作为单元素列表返回,而不是字符串。只需将其更改为字符串,现在一切正常...感谢您与我一起思考。
  • 对,我正要说你链接的例子使用.extract_first(),而不是.extract()

标签: python pagination scrapy


【解决方案1】:

似乎是一个愚蠢的错误:

 for href in response.xpath(
        '//*[@id="maincontent"]/ul/li/article/header[1]',
        ).css('a::attr(href)').extract():

提供一个包含分页href的单元素列表,例如['\href']。但是要使代码正常工作,需要一个字符串,例如'\href'。因此,在上面的代码 sn -p 中,将extract() 替换为extract()[0]

【讨论】:

  • 惯用的方式是使用.extract_first()。当没有匹配项时,它有助于解决索引错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2013-11-30
相关资源
最近更新 更多