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 = arrow。
请您参考如下方法:
使用 .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()
