工程目录结构

 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文件中持久化存储的更多相关文章

  1. python_爬虫一之爬取糗事百科上的段子

    目标 抓取糗事百科上的段子 实现每按一次回车显示一个段子 输入想要看的页数,按 'Q' 或者 'q' 退出 实现思路 目标网址:糗事百科 使用requests抓取页面  requests官方教程 使用 ...

  2. python爬虫29 | 使用scrapy爬取糗事百科的例子,告诉你它有多厉害!

    是时候给你说说 爬虫框架了 使用框架来爬取数据 会节省我们更多时间 很快就能抓取到我们想要抓取的内容 框架集合了许多操作 比如请求,数据解析,存储等等 都可以由框架完成 有些小伙伴就要问了 你他妈的 ...

  3. 芝麻HTTP:Python爬虫实战之爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  4. python 爬虫实战1 爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 本篇目标 抓取糗事百科热门段子 过滤带有图片的段子 实现每按一次回车显示一个段子的发布时间,发布人 ...

  5. Python爬虫实战之爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  6. Python爬虫实战之爬取糗事百科段子【华为云技术分享】

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  7. 21天打造分布式爬虫-Spider类爬取糗事百科(七)

    7.1.糗事百科 安装 pip install pypiwin32 pip install Twisted-18.7.0-cp36-cp36m-win_amd64.whl pip install sc ...

  8. 2019基于python的网络爬虫系列,爬取糗事百科

    **因为糗事百科的URL改变,正则表达式也发生了改变,导致了网上许多的代码不能使用,所以写下了这一篇博客,希望对大家有所帮助,谢谢!** 废话不多说,直接上代码. 为了方便提取数据,我用的是beaut ...

  9. scrapy 爬取糗事百科

    安装scrapy conda install scrapy 创建scrapy项目 scrapy startproject qiubai 启动pycharm,发现新增加了qiubai这个目录 在spid ...

随机推荐

  1. 跟我学算法聚类(DBSCAN)

    DBSCAN 是一种基于密度的分类方法 若一个点的密度达到算法设定的阖值则其为核心点(即R领域内点的数量不小于minPts) 所以对于DBSCAN需要设定的参数为两个半径和minPts 我们以一个啤酒 ...

  2. 笔记-TCPCLIENT

    ]; private void ReceiveMessage() { try { tcpClient = );//创建TcpClient对象实例 } catch (Exception le) { } ...

  3. avalon 的HTML规范

    由于avalon以绑定属性实现对DOM的选择与操作,页面的美观与调试就变得至关重要.参照boostrap的HTML规范,制定如下 属性排列的规范 class (class, id, name与浏览器的 ...

  4. SPI子系统分析之二:数据结构

    内核版本:3.9.5 spi_master struct spi_master用来描述一个SPI主控制器,我们一般不需要自己编写spi控制器驱动. /*结构体master代表一个SPI接口,或者叫一个 ...

  5. Python中的try...except...finally

    Python的异常处理代码格式如下: try: // do something except Exception as e: // dual with exception finally: // fi ...

  6. linux:alias

    linux系统下常用一个“命令”ll,它实质上是一个别名,而非命令. 我们用它的前提是,在~/.bashrc文件里打开,默认有条记录: #alias ll=’ls -l’ 这就是别名的格式.把注释去掉 ...

  7. 【祥哥带你玩HoloLens开发】了解如何实现远程主机为HoloLens实时渲染

    今天有一个兄弟在群里讲到他们的项目模型比较大,单用HoloLens运行设备的性能无法满足需要,问道如何将渲染工作交给服务器来做,讲渲染结果传给HoloLens.正好刚刚看官方github的时候发现一个 ...

  8. Docker03 Docker基础知识、Docker实战

    1 Docker基础知识 1.1 什么是Docker Docker是一个可以装应用的容器,就像杯子可以装水.书包可以装书一样:docker官网 Docker是Docker公司开发的,并开源到GitHu ...

  9. Linux下各种解压命令

    本文介绍了linux下的压缩程式tar.gzip.gunzip.bzip2.bunzip2.compress .uncompress. zip. unzip.rar.unrar等程式,以及如何使用它们 ...

  10. Opencv 发现轮廓 findContours

    vector<vector<Point>> vec_p; vector<Vec4i> vec_4f; findContours(img_canny1, vec_p, ...