练手实例:Scrapy爬取一本完整小说(章节乱序问题解决)

戳这里查看此小说
整体都很简单,没啥多说的,10分钟搞定
外循环在主页面找url进行拼接,小循环解析详细页内容提取小说文本。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
biquge.py

import scrapy
from scrapy.selector import Selector

class BiqugeSpider(scrapy.Spider):
    name = 'biquge'
    allowed_domains = ['biquge.info']
    start_urls = ['https://www.biquge.info/34_34370/']

    def parse(self, response):
        selector = Selector(response)
        find_all = selector.xpath("/html/body/div[@id='wrapper']/div[@class='box_con'][2]/div[@id='list']/dl/dd")
        for section in find_all:
            href = section.xpath('.//@href').extract_first()
            real_url = response.urljoin(href)
            request = scrapy.Request(real_url,callback=self.parse_detail)
            yield request
            # print(real_url)测试成功


    def parse_detail(self,response):
        selector = Selector(response)
        content_list = selector.xpath('//div[@id="content"]/text()').extract()
        # for real in content:
            # print(real)测试成功
        content = '\n'.join(content_list)
        item = dict()
        item['content'] = content
        print(content)
        yield item
        

itempipins.py

class XiaoshuoPipeline(object):
    def __init__(self):
        self.file = open('D://女帝直播攻略.txt','a+',encoding='utf-8')
        
    def process_item(self, item, spider):
        self.file.write(item['content'])
        return item

settings.py

LOG_LEVEL = 'WARNING'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'

结果
在这里插入图片描述
在这里插入图片描述
真的不得不佩服scrapy的速度,太猛了,上了个厕所就爬完了一千七百多章。。


-----------------------------------------------------华丽的分割线-------------------------------------------------------------

由于很多小伙伴反应因为多线程的问题而导致scrapy爬取的小说章节乱序的问题,此处分享一个解决方法

增加两个东西:

1.设定一个全局变量,以章节序号作为键,以章节内容作为值
2.重写scrapy的close方法,按顺序遍历章节,并写入文件,或者保存到本地

项目地址 https://gitee.com/py_lzx/spider_lzx

  • 3
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 27
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值