【问题标题】:Extract all pagination links to pages with scrapy?使用scrapy提取所有指向页面的分页链接?
【发布时间】:2017-12-13 23:19:36
【问题描述】:
import scrapy
class QuotesSpider(scrapy.Spider):
    name = 'quotes'
    allowed_domains = ['www.onthemarket.com']
    start_urls = ['https://www.onthemarket.com/for-sale/property/london/']
    def parse(self, response):
        next_page_url = response.css("li > a.arrow::attr(href)").extract_first()

        if next_page_url:
            next_page_url = response.urljoin(next_page_url)
            yield scrapy.Request(url=next_page_url, callback=self.parse)

        print(next_page_url)

我需要一个包含所有指向下一页的链接的列表。如何遍历所有分页链接并用scrapy提取?他们都有 class= 箭头。

【问题讨论】:

  • 如果页面使用 JavaScript 添加分页,那么您需要Selenium 来控制将运行 JavaScript 的 Web 浏览器。或者你必须找到JavaScript用来获取数据的url,然后你才能从这个url中读取所有内容。
  • 你不能把它放在标准列表中吗?或者通常yield每个链接并运行代码并选择保存在文件中,您将获得文件中的所有链接。
  • 您不必搜索“下一页” - 它始终是 extract() 中的最后一项
  • 或者你可以试试 CSS 选择器:last-child

标签: python scrapy scrapy-spider


【解决方案1】:

为了在使用scrapy 时找到并准备好链接,我始终建议使用LinkExtractor

from scrapy.linkextractors import LinkExtractor

...
    def parse(self, response):
        ...
        le = LinkExtractor(restrict_css=['li > a.arrow'])
        for link in le.extract_links(response):
            yield Request(link.url, callback=self.parse)

您可以将它与许多不同的过滤器一起使用,例如正则表达式、xpath,甚至可以确定链接到底在哪个标签中(默认情况下它会找到a 标签)

【讨论】:

    【解决方案2】:

    使用.extract_first(),您总是会在分页中获得第一个链接,即指向第一页或第二页的链接。

    使用.extract()[-1],您会在分页中获得指向下一页的最后一个链接。

    next_page_url = response.css("li > a.arrow::attr(href)").extract()[-1]
    

    编辑: 或者您可以使用 CSS 选择器 :last-child(与 .extract_first()

    next_page_url = response.css("li > a.arrow:last-child::attr(href)").extract_first()
    

    编辑: 或使用 xpath 和 [last()]

    next_page_url = response.xpath('(//li/a[@class="arrow"]/@href)[last()]').extract_first()
    

    next_page_url = response.xpath('(//li/a[@class="arrow"])[last()]/@href').extract_first()
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      相关资源
      最近更新 更多