Python3 爬虫 scrapy框架 爬取小说网站数据

上次用requests写的爬虫速度很感人,今天打算用scrapy框架来实现,看看速度如何。

爬虫步骤

第一步,安装scrapy,执行一下命令

pip install Scrapy

第二步,创建项目,执行一下命令

scrapy startproject novel

第三步,编写spider文件,文件存放位置novel/spiders/toscrape-xpath.py,内容如下

# -*- coding: utf-8 -*-
import scrapy


class ToScrapeSpiderXPath(scrapy.Spider):
    # 爬虫的名字
    name = 'novel'
    # 爬虫启始url
    start_urls = [
        'https://www.xbiquge6.com/0_638/1124120.html',
    ]

    def parse(self, response):
        # 定义存储的数据格式
        yield {
            'text': response.xpath('//div[@class="bookname"]/h1[1]/text()').extract_first(),
            'content': response.xpath('//div[@id="content"]/text()').extract(),
            # 'author': quote.xpath('.//small[@class="author"]/text()').extract_first(),
            # 'tags': quote.xpath('.//div[@class="tags"]/a[@class="tag"]/text()').extract()
        }
        # 下一章的链接
        next_page_url = response.xpath('//div[@class="bottem1"]/a[3]/@href').extract_first()
        # 如果下一章的链接不等于首页 则爬取url内容  ps:最后一章的下一章链接为首页
        if next_page_url != 'https://www.xbiquge6.com/0_638/':
            yield scrapy.Request(response.urljoin(next_page_url))

总结

框架用时:23分,比requests快三倍!awesmome!xpath也蛮好用的,继续学习,欢迎交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值