工程目录结构

 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. Python 位运算符 逻辑运算符 成员运算符

    位运算符 运算符 描述 实例 & 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 (a & b) 输出结果12 ,二进制解释:0000 1100 | ...

  2. Halcon标定

    摄像头拍摄时候,图像均有畸变,但是图像的扭曲变形均是有规律的成线性的,所以可以通过算法矫正.halcon标定过程需要在镜头内放置标定板:标定板一般选用30*30mm的:可以通过halcon程序来制作: ...

  3. 解决SDK未授权问题

    问题描述 在启动项目的时候报错了,如下: What went wrong: A problem occurred configuring project ':app'. > You have n ...

  4. svn与eclipse的集成(第三方插件与eclipse的集成)

    在eclipse中点击Help,选中install  from site..

  5. Asp.net 使用Neatupload 第三方控件上传大文件,在IIS7上无法正常工作解决

    使用环境:Window Server2008 + IIS7 更改web.config配置 1.在<configSections></configSections>节内加入: & ...

  6. centos7 安装mysql5.6.32

    1.  检查是否存在旧的mysql,执行: rpm -qa|grep -i mysql PS:若存在旧mysql,删除查询到的旧mysql,执行: rpm -e --nodeps  XXXX      ...

  7. Nginx源码完全注释(6)core/murmurhash

    下面是摘自 Google Code 的 Murmurhash 开源项目主页上的 Murmurhash2,Nginx 就是采用的这个. uint32_t MurmurHash2 ( const void ...

  8. Cannot subclass final class class com.sun.proxy.$Proxy16

    Cannot subclass final class class com.sun.proxy.$Proxy16 2016年05月04日 19:10:58 阅读数:15028 背景 这个错误是我在使用 ...

  9. C++ std::vector

    std::vector template < class T, class Alloc = allocator<T> > class vector; // generic te ...

  10. Python3 urllib.parse 常用函数示例

    Python3 urllib.parse 常用函数示例 http://blog.51cto.com/walkerqt/1766670  1.获取url参数. >>> from url ...