爬虫--使用scrapy爬取糗事百科并在txt文件中持久化存储
工程目录结构
spiders下的first源码
# -*- coding: utf- -*-
import scrapy
from firstBlood.items import FirstbloodItem
class FirstSpider(scrapy.Spider):
#爬虫文件的名称
#当有多个爬虫文件时,可以通过名称定位到指定的爬虫文件
name = 'first'
#allowed_domains 允许的域名 跟start_url互悖
#allowed_domains = ['www.xxx.com']
#start_url 请求的url列表,会被自动的请求发送
start_urls = ['https://www.qiushibaike.com/text/']
def parse(self, response):
'''
解析请求的响应
可以使用正则,XPATH ,因为scrapy 集成了XPATH,建议使用XAPTH
解析得到一个selector
:param response:
:return:
'''
all_data = []
div_list=response.xpath('//div[@id="content-left"]/div')
for div in div_list:
#author=div.xpath('./div[1]/a[2]/h2/text()')#author 拿到的不是之前理解的源码数据而
# 是selector对象,我们只需将selector类型对象下的data对象拿到即可
#author=author[].extract()
#如果存在匿名用户时,将会报错(匿名用户的数据结构与登录的用户名的数据结构不一样)
''' 改进版''' author = div.xpath('./div[1]/a[2]/h2/text()| ./div[1]/span[2]/h2/text()')[].extract()
content=div.xpath('.//div[@class="content"]/span//text()').extract()
content=''.join(content)
#print(author+':'+content.strip(' \n \t ')) #基于终端的存储
# dic={
# 'author':author,
# 'content':content
# }
# all_data.append(dic)
# return all_data
#持久化存储的两种方式
# 基于终端指令:parse方法有一个返回值
#scrapy crawl first -o qiubai.csv --nolog
#终端指令只能存储json,csv,xml等格式文件
#2基于管道
item = FirstbloodItem()#循环里面,每次实例化一个item对象
item['author']=author
item['content']=content
yield item #将item提交给管道
Items文件
# -*- coding: utf- -*- # Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html import scrapy class FirstbloodItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
#item类型对象 万能对象,可以接受任意类型属性,字符串,json等
author = scrapy.Field()
content = scrapy.Field()
pipeline文件
# -*- coding: utf- -*- # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html #只要涉及持久化存储的相关操作代码都需要写在该文件种
class FirstbloodPipeline(object):
fp=None
def open_spider(self,spider):
print('开始爬虫')
self.fp=open('./qiushibaike.txt','w',encoding='utf-8')
def process_item(self, item, spider):
'''
处理Item
:param item:
:param spider:
:return:
'''
self.fp.write(item['author']+':'+item['content'])
print(item['author'],item['content'])
return item
def close_spider(self,spider):
print('爬虫结束')
self.fp.close()
Setting文件
# -*- coding: utf- -*- # Scrapy settings for firstBlood 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 = 'firstBlood' SPIDER_MODULES = ['firstBlood.spiders']
NEWSPIDER_MODULE = 'firstBlood.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent
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
#默认为True ,改为False 不遵从ROBOTS协议 反爬
ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: )
#CONCURRENT_REQUESTS = # Configure a delay for requests for the same website (default: )
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY =
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN =
#CONCURRENT_REQUESTS_PER_IP = # 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 = {
# 'firstBlood.middlewares.FirstbloodSpiderMiddleware': ,
#} # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'firstBlood.middlewares.FirstbloodDownloaderMiddleware': ,
#} # 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 = {
'firstBlood.pipelines.FirstbloodPipeline': ,# 为优先级
} # 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 =
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY =
# 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 =
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
爬虫--使用scrapy爬取糗事百科并在txt文件中持久化存储的更多相关文章
- python_爬虫一之爬取糗事百科上的段子
目标 抓取糗事百科上的段子 实现每按一次回车显示一个段子 输入想要看的页数,按 'Q' 或者 'q' 退出 实现思路 目标网址:糗事百科 使用requests抓取页面 requests官方教程 使用 ...
- python爬虫29 | 使用scrapy爬取糗事百科的例子,告诉你它有多厉害!
是时候给你说说 爬虫框架了 使用框架来爬取数据 会节省我们更多时间 很快就能抓取到我们想要抓取的内容 框架集合了许多操作 比如请求,数据解析,存储等等 都可以由框架完成 有些小伙伴就要问了 你他妈的 ...
- 芝麻HTTP:Python爬虫实战之爬取糗事百科段子
首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...
- python 爬虫实战1 爬取糗事百科段子
首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 本篇目标 抓取糗事百科热门段子 过滤带有图片的段子 实现每按一次回车显示一个段子的发布时间,发布人 ...
- Python爬虫实战之爬取糗事百科段子
首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...
- Python爬虫实战之爬取糗事百科段子【华为云技术分享】
首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...
- 21天打造分布式爬虫-Spider类爬取糗事百科(七)
7.1.糗事百科 安装 pip install pypiwin32 pip install Twisted-18.7.0-cp36-cp36m-win_amd64.whl pip install sc ...
- 2019基于python的网络爬虫系列,爬取糗事百科
**因为糗事百科的URL改变,正则表达式也发生了改变,导致了网上许多的代码不能使用,所以写下了这一篇博客,希望对大家有所帮助,谢谢!** 废话不多说,直接上代码. 为了方便提取数据,我用的是beaut ...
- scrapy 爬取糗事百科
安装scrapy conda install scrapy 创建scrapy项目 scrapy startproject qiubai 启动pycharm,发现新增加了qiubai这个目录 在spid ...
随机推荐
- 使用C#书写SQLite数据库增删改查语句(以及插入byte[]时遇到的问题总结)
在没有使用SQLite这种轻量级的数据库之前,只使用过Sqlserver2008进行数据的增删改查,公司使用的是大型的ORACLE数据库,还没有真正的会使用它.那时候觉得数据库很庞大,然而遇到SQLi ...
- Oracle11gR2导入导出实战之表空间传输
Oracle11gR2导入导出实战之使用Datapump进行表空间传输 表空间检查 [oracle@localhost database]$ ps -ef|grep smon oracle 8981 ...
- C#发送和接受POST请求
1.发送Post请求代码 /// <summary> /// 发起Http请求 /// </summary> /// <param name="flightDa ...
- java算法 第七届 蓝桥杯B组(题+答案) 9.取球博弈
9.取球博弈 (程序设计) 两个人玩取球的游戏.一共有N个球,每人轮流取球,每次可取集合{n1,n2,n3}中的任何一个数目.如果无法继续取球,则游戏结束.此时,持有奇数个球的一方获胜.如果两人都是 ...
- Inversions SGU - 180
这个是逆序对的裸题哇 归并排序或者树状数组~ 树状数组的话需要离散化一下··· emm确实很水很水很水··· 归并排序: #include <cstdio> #include <al ...
- jmeter-plugins-dubbo & DevToolBox
jmeter-plugins-dubbo使用 A. 下载jmeter并安装,http://jmeter.apache.org/download_jmeter.cgi(文中使用的版本是3.3,理论上高版 ...
- rsyslog收集nginx日志配置
rsyslog日志收集配置 rsyslog服务器收集各服务器的日志,并汇总,再由logstash处理 请查看上一篇文章 http://bbotte.blog.51cto.com/6205307/16 ...
- jQuery中deferred对象的使用(一)
在jquery1.5之后的版本中,加入了一个deferred对象,也就是延迟对象,用来处理未来某一时间点发生的回调函数.同时,还改写了ajax方法,现在的ajax方法返回的是一个deferred对象. ...
- c++ static笔记
[转]http://www.cnblogs.com/zi-xing/p/4590282.html static的作用 在函数体,一个被声明为static的变量,在这一函数被调用的过程里,其数值维持不变 ...
- 点云数据保存为pcd文件_pcd_write.cpp
#include <iostream>#include <pcl/io/pcd_io.h>#include <pcl/point_types.h> int main ...