前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 爬虫 scrapy框架

Python3 爬虫 scrapy框架

作者头像
py3study
发布2020-01-02 17:52:59
3980
发布2020-01-02 17:52:59
举报
文章被收录于专栏:python3

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

爬虫步骤

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

代码语言:javascript
复制
pip install Scrapy

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

代码语言:javascript
复制
scrapy startproject novel

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

代码语言:javascript
复制
# -*- 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也蛮好用的,继续学习,欢迎交流。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 爬虫步骤
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档