Scray爬取小说

 1.创建一个scrapy项目

scrapy startproject dingdianxiaoshuo

进入到项目里

cd + 项目路径

创建CrawlSpider

scrapy genspider -t crawl 爬虫名 (allowed_url)
scrapy genspider -t crawl xs ddyueshu.com

创建一个窗口

code .

2.编写wallpaper.py文件

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
"""
使用scrapycrawl类爬取小说数据
"""
class XsSpider(CrawlSpider):
    name = "xs"
    allowed_domains = ["ddyueshu.com"]
    start_urls = ["https://www.ddyueshu.com/1_1651/"]

    rules = (
        Rule(LinkExtractor(restrict_xpaths="//div[@class='box_con']/div/dl/dd[7]/a"),callback="parse_item",follow=True),
        Rule(LinkExtractor(restrict_xpaths="//div[@class='bottem2']/a[3]"), callback="parse_item", follow=True)
        )

    def parse_item(self, response):
        title = response.xpath("//div[@class='bookname']/h1/text()").get()
        content = response.xpath("//div[@id='content']/text()").extract()

        yield{
            'title':title,
            'content':content
        }

Rule分别定位小说第一章的xpath链接和下一章链接的xpath,因为使用scrapycrawl类爬取小说要是在第一章的里面(第一章 外门弟子_修罗武神_玄幻小说_顶点小说 (ddyueshu.com))开始爬取数据会丢失第一章的数据,所以要在上一层(修罗武神最新章节_修罗武神无弹窗全文阅读_顶点小说 (ddyueshu.com))开始。

3.配置settings.py文件

添加useragent,把robot协议注释,每爬取一页等待2秒,打开管道

4.编写pipeline.py文件

from itemadapter import ItemAdapter
import re

class DingdianxiaoshuoPipeline:
    def open_spider(self,spider):
        self.file = open('xiaoshuo.txt','w',encoding='utf-8')
    def process_item(self, item, spider):
       self.file.write(item['title'])
        #item返回的是列表类型,需要转换成字符串才能写入
       content = self.file.write((re.sub(r'\t+','\n',''.join(item['content'])))+'\n\n\n')
       self.file.flush()
       return item
    def close_spider(self,spider):
        self.file.close()

效果展示

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值