python爬虫–scrapy(初识)

python爬虫–scrapy(初识)

python爬虫–scrapy(初识)

scrapy环境安装

因为我是同时安装anaconda和python3.7,所以在使用pip的时候总是会显示anaconda中已经安装(众所周知),就很烦 。一气之下,挂着VPN并且在CMD中使用conda install scrapy,然后安装好。
PS:也有可能直接使用conda install scrapy就可以了(我没试)

最近又在试发现直接cd到python目录下,并且我已经安装python3.8,更新pip,然后pip install scrapy就成功了。没有冲突一说。
出现下面这张图后,就说明已经安装完成
在这里插入图片描述

scrapy基本使用

使用命令行创建scrapy项目工程scrapy startproject qiushi就会提示你创建成功

在这里插入图片描述
然后提示你cd到该目录下,并且创建first spider

命令scrapy genspider example example
在这里插入图片描述
配置文件的修改
在这里插入图片描述
在这里插入图片描述

别忘了user-Agent

运行项目文件

#终端输入
scrapy crawl first

在这里插入图片描述

糗事百科数据解析

import scrapy


class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.qiushibaike.com/text/']

    def parse(self, response):
        div_list = response.xpath('//*[@id="content"]/div/div[2]/div')
        for div in div_list:
            #xpath返回的是列表,但是列表元素一定是Selector类型的对象
            #extract可以将Selector对象中的data参数存储的字符串提取出来

            #author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
            #.extract_first()是确定列表中只存在一个元素
            author  = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = div.xpath('./a[1]/div/span/text()').extract()
            content = ''.join(content)
            print(author,content)
            break

效果图
在这里插入图片描述

持久化存储

基于终端指令的持久化存储

import scrapy
from qiushi.items import QiushiItem

class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.qiushibaike.com/text/']
    def parse(self, response):
        div_list = response.xpath('//*[@id="content"]/div/div[2]/div')
        all_data = []
        for div in div_list:
            #xpath返回的是列表,但是列表元素一定是Selector类型的对象
            #extract可以将Selector对象中的data参数存储的字符串提取出来

            #author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
            author  = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = div.xpath('./a[1]/div/span/text()').extract()
            content = ''.join(content)
            dic = {
   
                'author':author,
                'content':content
            }
            all_data.append(dic)
        return all_data

终端命令:scrapy crawl qiubai -o qiushi.csv

#终端命令
(acoda) D:\桌面\acodascrapy模块\qiushi>scrapy crawl qiubai -o qiushi.csv
开始爬虫。。。。
爬虫结束!!!

在这里插入图片描述

需注意的是:基于终端命令存储,只能存储(‘json’, ‘jsonlines’, ‘jl’, ‘csv’, ‘xml’, ‘marshal’, ‘pickle’)后缀的名称

在这里插入图片描述

基于管道的持久化存储

  1. 数据解析

  2. 在item类中定义相关的属性

  3. 将解析的数据封装存储到item类型的对象

  4. 将item类型的对象提交给管道进行持久化存储的操作

  5. 在管道类的process_ item中要将其接受到的item对象中存储的数据进行持久化存储操作

  6. 在配置文件中开启管道

步骤1and3and4爬虫文件

import scrapy
from qiushi.items import QiushiItem#导入QiushiItem类

class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    #allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.qiushibaike.com/text/']
    def parse(self, response):
        div_list = response.xpath('//*[@id="content"]/div/div[2]/div')
        all_data = []
        for div in div_list:
            #xpath返回的是列表,但是列表元素一定是Selector类型的对象
            #extract可以将Selector对象中的data参数存储的字符串提取出来

            #author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
            author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = div.xpath('./a[1]/div/span/text()').extract()
            content = ''.join(content)

            item = QiushiItem(author=author, content=content)
            # item['author'] = author
            # item['content'] = content
			#将item类型的对象提交给管道进行持久化存储的操作
            yield item

步骤2items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class QiushiItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()
    #pass

步骤5pipelines.py

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

class QiushiPipeline:
    fp = open('./qiushi.txt','w',encoding='utf-8')
    #重写父类的一个方法:该方法只在爬虫开始的时候被调用一次
    def open_spider(self, spider):
        print('开始爬虫。。。。')
        fp = open('./qiushi.txt','w',encoding='utf-8')

    def close_spider(self,spider):
        print('爬虫结束!!!')
        self.fp.close()
    def process_item(self, item, spider):
        author = item['author']
        content = item['content']
        self.fp.write(author+content)
        return item


步骤6setting.py

ITEM_PIPELINES = {
   
   'qiushi.pipelines.QiushiPipeline': 300,
}#300表示优先级,数值越大优先级越高

注意:open_spider(self, spider),close_spider(self,spider)是之前定义好在QiushiPipeline这个父类的
在这里插入图片描述
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/100094.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • Linux最著名的文本编辑器,最优秀的5个Linux文本编辑器

    Linux最著名的文本编辑器,最优秀的5个Linux文本编辑器Vi/VimEditorVim以绝对优势获胜在大家的意料之中。如果你不熟悉最好的5个Linux文本编辑器中的任何一个,阅读本文剩下的部分对那些编辑器多点了解。1.VimEditor最新稳定版本:Vim7.2用C和Vimscript编写操作系统:跨平台(Unix,LinuxandWindows)阅读我们正在连载的Vi/Vim技巧和诀窍系列文章,掌握一些很棒的Vim绝…

  • Self-Host c#学习笔记之Application.DoEvents应用 不用IIS也能執行ASP.NET Web API

    Self-Host c#学习笔记之Application.DoEvents应用 不用IIS也能執行ASP.NET Web APISelf-Host c#学习笔记之Application.DoEvents应用 不用IIS也能執行ASP.NET Web API

  • gulp pipe缓存_gulp使用教程

    gulp pipe缓存_gulp使用教程首先,gulp的源码里没有任何一部分是定义pipe的。gulp的pipe方法是来自nodejsstreamAPI的。gulp本身是由一系列vinyl模块组织起来的。pipe方法到底是什么呢?pipe跟他字面意思一样只是一个管道例如我有一堆文件var s=gulp.src(["fileA","fileB","fileC"])src方法实际上是’vinyl-fs’模…

  • Java线程(五):Timer和TimerTask

    Timer和TimerTask可以做为实现线程的第三种方式,前两中方式分别是继承自Thread类和实现Runnable接口。Timer是一种线程设施,用于安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行,可以看成一个定时器,可以调度TimerTask。TimerTask是一个抽象类,实现了Runnable接口,所以具备了多线程的能力。…

  • HTML5新控件 – 日期和时间选择输入

    HTML5新控件 – 日期和时间选择输入转载自:https://blog.csdn.net/u014063717/article/details/50914466HTML5定义了几个与日期有关的新控件。支持日期控件的浏览器会提供一个方便的下拉式日历,供用户选择。注意:我测试了Chrome和Opera,火狐提供下拉式日历支持,其它浏览器可能仍是一个普通文本框。1,日期控件-date<inputtype="date"valu…

  • lea指令!「建议收藏」

    lea指令!「建议收藏」
    最近在看linux-0.11内核,看到lea这个指令,google搜索了一下,转给大家,一起学习@!
     
    先看这个这个语法格式吧:
    对AT&T来说,寻址方式比较怪异,但又非常简洁,语法格式如下:segreg:base_address(offset_address,index,size) ;例子movl%eax,label1(,$2,$4)movl%ebx,(label2,$2,)movl%ecx,(%esp)
    其效果为

    2022年10月25日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号