Python 将所有分页链接提取到使用scrapy的页面?

Python 将所有分页链接提取到使用scrapy的页面?,python,scrapy,scrapy-spider,Python,Scrapy,Scrapy Spider,我需要一个所有链接到下一页的列表。如何遍历所有分页链接并使用scrapy提取它们?他们都有class=arrow。 使用.extract_时,您总是会在分页中获得第一个链接,即指向第一页或第二页的链接 使用.extract[-1]可以获得分页中指向下一页的最后一个链接 import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' allowed_domains = ['www.onthemarket.com']

我需要一个所有链接到下一页的列表。如何遍历所有分页链接并使用scrapy提取它们?他们都有class=arrow。

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

使用.extract[-1]可以获得分页中指向下一页的最后一个链接

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)
编辑:或者您可以先使用CSS选择器和.extract_

编辑:或使用xpath和[last]

使用.extract_first,您始终可以获得分页中的第一个链接,即指向第一页或第二页的链接

使用.extract[-1]可以获得分页中指向下一页的最后一个链接

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)
编辑:或者您可以先使用CSS选择器和.extract_

编辑:或使用xpath和[last]


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


您可以将它与许多不同的过滤器(如正则表达式、xpath)一起使用,甚至可以确定链接默认情况下在哪个标记中查找标记,以便在使用scrapy时查找并准备好链接。我始终建议使用:


您可以将它与许多不同的过滤器(如正则表达式、xpath)一起使用,甚至可以确定默认情况下链接在哪个标记中找到标记。如果页面使用JavaScript添加分页,那么您需要Selenium来控制运行JavaScript的web浏览器。或者,您必须找到JavaScript用来获取数据的url,然后才能从该url读取所有内容。您不能将其保留在标准列表中吗?或者通常生成每个链接并运行带有保存在文件中选项的代码,您将获得文件中的所有链接。response.css应该选择下一页的标题,不知道如何在响应中实现它。css您不必搜索下一页-它始终是提取器中的最后一项。您可以尝试使用css选择器。如果页面使用JavaScript添加分页,那么您需要Selenium来控制将运行JavaScript的web浏览器。或者,您必须找到JavaScript用来获取数据的url,然后才能从该url读取所有内容。您不能将其保留在标准列表中吗?或者通常生成每个链接并运行带有保存在文件中选项的代码,您将获得文件中的所有链接。css应该选择下一页的标题,但不知道如何在响应中实现它。css您不必搜索下一页-它始终是提取器中的最后一项,您可以尝试使用css选择器
next_page_url = response.css("li > a.arrow:last-child::attr(href)").extract_first()
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()
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)