阅读目录:

上一篇持久化存储的博客中对于校花网的爬取已经运用到了递归爬取多页页面数据,下面我们在加一个例子在来回顾一下。

- 需求:将糗事百科所有页码的作者和段子内容数据进行爬取切持久化存储

- 需求分析:每一个页面对应一个url,则scrapy工程需要对每一个页码对应的url依次发起请求,然后通过对应的解析方法进行作者和段子内容的解析。

实现方案:

    1.将每一个页码对应的url存放到爬虫文件的起始url列表(start_urls)中。(不推荐)

    2.使用Request方法手动发起请求。(推荐)
# -*- coding: utf-8 -*-
import scrapy
from qiushibaike.items import QiushibaikeItem
# scrapy.http import Request
class QiushiSpider(scrapy.Spider):
    name = 'qiushi'
    allowed_domains = ['www.qiushibaike.com']
    start_urls = ['https://www.qiushibaike.com/text/']

    #爬取多页
    pageNum = 1 #起始页码
    url = 'https://www.qiushibaike.com/text/page/%s/' #每页的url

    def parse(self, response):
        div_list=response.xpath('//*[@>)
        for div in div_list:
            #//*[@]/div[1]/a[2]/h2
            author=div.xpath('.//div[@class="author clearfix"]//h2/text()').extract_first()
            author=author.strip('\n')
            content=div.xpath('.//div[@class="content"]/span/text()').extract_first()
            content=content.strip('\n')
            item=QiushibaikeItem()
            item['author']=author
            item['content']=content

            yield item #提交item到管道进行持久化

         #爬取所有页码数据
        if self.pageNum <= 13: #一共爬取13页(共13页)
            self.pageNum += 1
            url = format(self.url % self.pageNum)

            #递归爬取数据:callback参数的值为回调函数(将url请求后,得到的相应数据继续进行parse解析),递归调用parse函数
            yield scrapy.Request(url=url,callback=self.parse)
示例代码

相关文章:

  • 2022-12-23
  • 2022-01-26
  • 2021-10-15
  • 2022-12-23
  • 2021-05-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
猜你喜欢
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
相关资源
相似解决方案