通过相对路径获取下一页的链接

# -*- coding: utf-8 -*-
import scrapy
import re
from urllib.parse import urljoin

from ..items import ScrapyItem


class DocsScrapySpider(scrapy.Spider):
    name = 'docs.scrapy'
    allowed_domains = ['docs.scrapy.org']
    start_urls = ['https://docs.scrapy.org/en/latest/index.html']

    def parse(self, response):
        docs = response.xpath('//div[@class="document"]').extract_first()
        print(docs)
        scrapy_docs = ScrapyItem()
        scrapy_docs["docs_scrapy"] = docs
        yield scrapy_docs

        next_page = response.xpath('//a[@rel="next"]/@href').extract_first()
        if next_page:
            next_page = urljoin(response.url, next_page)
            print(next_page)
            yield response.follow(next_page, self.parse)

urljoin

  1. 引入urllib.parse模块下的urljoin,
  2. 获取当前页的链接response.url
  3. 将当前页的地址和下一页的相对路径地址拼接,从而获取下一页的链接

转载于:https://www.cnblogs.com/chenliang0309/p/10030723.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值