day26-爬虫-scrapy框架初识
1.框架了解:高性能的异步下载、解析、持久化存储 2.下载安装,创建项目----------- pip install wheel Twisted 5步安装!
二.安装Linux:pip3 install scrapyWindows:a. pip3 install wheelb. 下载twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted c. 进入下载目录,执行 pip3 install Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whld. pip3 install pywin32e. pip3 install scrapy
scrapy startproject 项目名称 3.项目使用--5步听视频总结: 1.新建工程 scrapy startproject fristBlood 2.cd fristBlood 新建爬虫文件scrapy genspider chouti www.chouti.com(在spiders中会新增一个chouti.py,注意名称、start_url,注释#allowed_domains) 3.在chouti.py中进行parse方法的编写 4.配置文件的配置:在settings中进行UA伪装、ROBOTSTXT_OBEY = False 5.配置完后,在cmd中执行:scarpy crawl 爬虫文件名称 1.爬取chouti fristBlood
![](/assets/blank.gif)
![](/assets/blank.gif)
# -*- coding: utf-8 -*- import scrapyclass ChoutiSpider(scrapy.Spider):#爬虫文件的名称:可以指定某一个具体的爬虫文件name = 'chouti'#允许的域名:#allowed_domains = ['www.chouti.com']#起始url列表:工程被执行后就可以获取该列表中url所对应的页面数据start_urls = ['https://dig.chouti.com/']#该方法作用:就是讲起始url列表中指定url对应的页面数据进行解析操作#response参数:就是对起始url发起请求后对应的响应对象def parse(self, response):print(response)
chouti.py
2.爬取糗百 ---注意parse中 qiubaiPro #extract()可以将selector对象中存储的文本内容获取 封装一个可迭代类型 基于终端指令执行 scarpy crawl -o data.csv qiubai --nolog---不常用
![](/assets/blank.gif)
![](/assets/blank.gif)
# -*- coding: utf-8 -*- import scrapyclass QiubaiSpider(scrapy.Spider):name = 'qiubai'#allowed_domains = ['www.fdsfds.com']start_urls = ['https://www.qiushibaike.com/text/']def parse(self, response):#xpath返回的列表元素类型为Selecor类型div_list = response.xpath('//div[@id="content-left"]/div')#声明一个用于存储解析到数据的列表all_data = []for div in div_list:#extract()可以将selector对象中存储的文本内容获取#author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()author = div.xpath('./div[1]/a[2]/h2/text()').extract_first() #取出第一个元素,不用[0]了--意义同上行content = div.xpath('.//div[@class="content"]/span//text()').extract() #//text获取的内容不止一个,extract()获取多个列表内容content = "".join(content) #将列表转化成字符串dict = {'author':author,'content':content}all_data.append(dict)return all_data#持久化存储方式:#1.基于终端指令:必须保证parse方法有一个可迭代类型对象的返回#2.基于管道
qiubai.py
3.爬取糗百--基于管道执行--注意item pipeLinepropipelines.py编写在settings中开启ITEM_PIPELINES 67-69行 ITEM_PIPELINES数值越小,优先级越高(管道中) 一个写到磁盘,一个写到数据库中 屏蔽日志信息 scarpy crawl chouti --nolog cls清屏
![](/assets/blank.gif)
![](/assets/blank.gif)
import scrapyclass PipelineproItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()author = scrapy.Field()content = scrapy.Field()
items.py
![](/assets/blank.gif)
![](/assets/blank.gif)
# -*- coding: utf-8 -*-# Scrapy settings for pipeLinePro project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'pipeLinePro'SPIDER_MODULES = ['pipeLinePro.spiders'] NEWSPIDER_MODULE = 'pipeLinePro.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'pipeLinePro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False# Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default) #COOKIES_ENABLED = False# Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False# Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #}# Enable or disable spider middlewares # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'pipeLinePro.middlewares.PipelineproSpiderMiddleware': 543, #}# Enable or disable downloader middlewares # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'pipeLinePro.middlewares.PipelineproDownloaderMiddleware': 543, #}# Enable or disable extensions # See https://doc.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #}# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = {'pipeLinePro.pipelines.PipelineproPipeline': 300,'pipeLinePro.pipelines.MyPipeline': 301, }# Enable and configure the AutoThrottle extension (disabled by default) # See https://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default) # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
settings.py
![](/assets/blank.gif)
![](/assets/blank.gif)
# -*- coding: utf-8 -*- import scrapy from pipeLinePro.items import PipelineproItemclass QiubaiSpider(scrapy.Spider):name = 'qiubai'#allowed_domains = ['www.ds.com']start_urls = ['https://www.qiushibaike.com/text/']def parse(self, response):# xpath返回的列表元素类型为Selecor类型div_list = response.xpath('//div[@id="content-left"]/div')# 声明一个用于存储解析到数据的列表all_data = []for div in div_list:# extract()可以将selector对象中存储的文本内容获取# 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('.//div[@class="content"]/span//text()').extract()content = "".join(content)#实例化item对象item = PipelineproItem()#将解析到的数据值存储到item对象中item['author'] = authoritem['content'] = content#将item对象提交给管道yield item# 持久化存储方式:# 1.基于终端指令:必须保证parse方法有一个可迭代类型对象的返回# 2.基于管道:#1.items.py:对该文件中的类进行实例化操作(item对象:存储解析到的数据值)。#2.pipeline.py:管道,作用就是接受爬虫文件提交的item对象,然后将该对象中的数据值进行持久化存储操作
qiubai.py-管道
![](/assets/blank.gif)
![](/assets/blank.gif)
# -*- coding: utf-8 -*-import pymysqlclass PipelineproPipeline(object):#作用:每当爬虫文件向管道提交一次item,该方法就会被调用一次。item参数就是接受到爬虫文件给提交过来的item对象#该方法只有在开始爬虫的时候被调用一次fp = Nonedef open_spider(self,spider): #父类的方法print('开始爬虫')self.fp = open('./qiubai_data.txt', 'w', encoding='utf-8')def process_item(self, item, spider): #父类的方法author = item['author']content = item['content']self.fp.write(author+":"+content)return item#该方法只有在爬虫结束后被调用一次def close_spider(self,spider): #父类的方法print('爬虫结束')self.fp.close()class MyPipeline(object):conn = Nonecursor = None# 作用:每当爬虫文件向管道提交一次item,该方法就会被调用一次。item参数就是接受到爬虫文件给提交过来的item对象def open_spider(self,spider):self.conn = pymysql.Connect(host="192.168.12.65", port=3306, db="scrapyDB", charset="utf8", user="root")self.cursor = self.conn.cursor()print('mysql')def process_item(self, item, spider):author = item['author']content = item['content']sql = "insert into qiubai values('%s','%s')" % (author,content) #qiubai是表名try:self.cursor.execute(sql) #执行sqlself.conn.commit() #事务的处理,没有问题提交,有问题回滚except Exception as e:print(e)self.conn.rollback()return item
pipelines.py
管道操作4步---听视频自己总结: 前提要在parse方法中获取解析到的数据, 1.将解析到的数据值存储到item对象中(前提item中要进行属性的声明), 2.使用yield关键字将item对象提交给管道 3.在pipelines.py中进行PipelineproPipeline方法的编写,编写process_item 4.在配置文件中开启管道 1.#实例化item对象 item = PipelineproItem() 2.在items.py中声明属性 3.#将解析到的数据值存储到item对象中 item['author'] = author item['content'] = content 4.#将item对象提交给管道 yield item
将数据写入到数据库:新建数据库、表
select * from qiubai 查看写入的内容
转载于:https://www.cnblogs.com/lijie123/p/9998441.html
day26-爬虫-scrapy框架初识相关推荐
- Python爬虫-Scrapy框架(四)- 内置爬虫文件 - 4.2 初探Crawl Spider
Python爬虫-Scrapy框架(四)- 内置爬虫文件 - 4.2 初探Crawl Spider 写在前面 初探Crawl Spider 创建Crawl Spider项目 对比Basic与Crawl ...
- python cookie池_Python爬虫scrapy框架Cookie池(微博Cookie池)的使用
下载代码Cookie池(这里主要是微博登录,也可以自己配置置其他的站点网址) 下载代码GitHub:https://github.com/Python3WebSpider/CookiesPool 下载 ...
- python scrapy爬虫视频_python爬虫scrapy框架的梨视频案例解析
之前我们使用lxml对梨视频网站中的视频进行了下载 下面我用scrapy框架对梨视频网站中的视频标题和视频页中对视频的描述进行爬取 分析:我们要爬取的内容并不在同一个页面,视频描述内容需要我们点开视频 ...
- Python爬虫 scrapy框架爬取某招聘网存入mongodb解析
这篇文章主要介绍了Python爬虫 scrapy框架爬取某招聘网存入mongodb解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 创建项目 sc ...
- python爬虫--Scrapy框架--Scrapy+selenium实现动态爬取
python爬虫–Scrapy框架–Scrapy+selenium实现动态爬取 前言 本文基于数据分析竞赛爬虫阶段,对使用scrapy + selenium进行政策文本爬虫进行记录.用于个人爬虫学习记 ...
- Python爬虫—Scrapy框架—Win10下载安装
Python爬虫-Scrapy框架-Win10下载安装 1. 下载wheel 2.下载twisted 3. 下载pywin32 4. 下载安装Scrapy 5. 创建一个scrapy项目 6. fir ...
- python 爬虫框架_Python网络爬虫-scrapy框架的使用
1. Scrapy 1.1 Scrapy框架的安装 Scrapy是一个十分强大的爬虫框架,依赖的库比较多,至少需要依赖的库有Twisted .lxml和pyOpenSSL.在不同的平台环境下,它所依赖 ...
- dataObject可以去重吗java_python爬虫scrapy框架之增量式爬虫的示例代码
scrapy框架之增量式爬虫 一 .增量式爬虫 什么时候使用增量式爬虫: 增量式爬虫:需求 当我们浏览一些网站会发现,某些网站定时的会在原有的基础上更新一些新的数据.如一些电影网站会实时更新最近热门的 ...
- python爬虫scrapy框架爬取网页数据_Scrapy-Python
scrapy Scrapy:Python的爬虫框架 实例Demo 抓取:汽车之家.瓜子.链家 等数据信息 版本+环境库 Python2.7 + Scrapy1.12 初窥Scrapy Scrapy是一 ...
- scrapy获取a标签的连接_Python爬虫 scrapy框架初探及实战!
Scrapy框架安装 操作环境介绍 操作系统:Ubuntu19.10 Python版本:Python3.7.4 编译器:pycharm社区版 安装scrapy框架(linux系统下) 安装scrapy ...
最新文章
- 统计字符串中指定字符出现次数(Java)
- 强大Jquery插件,table排序之二
- AngularJS的稍复杂form验证
- 趣学python3(32)-enumerate,zip
- (王道408考研操作系统)第三章内存管理-第二节1:虚拟内存管理基本概念
- 【英语学习】【Level 07】U08 Old Stories L1 The old times
- leetcode题解279-完全平方数
- 23.6. Functions
- 996工作制,你能扛多久?
- Go语言躲坑经验总结
- 转摘 房地产知识
- pdf转换器免费版下载
- docker attach 和 exec 的区别
- 25 - 线程池和指令系统
- 初体验微信小程序记事本
- 2005岁末BLOG程序大评点
- 测试理论-测试用例设计 (一) --- 正交表分析法
- grpc报错: java.nio.channels.UnresolvedAddressException : null
- 艾永亮:耐克阿迪都慌了,成功逆袭的李宁,产品创新战略是什么
- 鹏城实验室开源技术总师余跃:新一代人工智能开源生态的探索与实践
热门文章
- 英文影视网站视频资讯文章采集批量翻译发布
- laravel mysql 数组_PHP如何使用laravel 5将数据从数组保存到mysql
- 2---理解正余弦、复数求模、反正切和乘除运算的CORDIC算法实现
- MySQL学习笔记3---Explain字段分析
- c语言 最佳情侣身高差
- AutoCAD.net-错误消息大全
- C#串口通讯+BigEndian+Little-Endian(大端和小端方案)
- ZOJ3587 Marlon's String KMP技巧处理
- 如何从微信跳到外部浏览器进行apk文件(app)下载
- c语言反三角函数值域,反三角函数值域