
- 外文名
- scrapy
- 基本功能
- 数据挖掘
- 特 点
- 应用框架
- 中文名
- 抓取
- 应 用
- 数据挖掘、监测和自动化测试
-
scrapy
2020-06-29 20:05:37scrapy 安装 scrapy 脚本 scrapy startproject mySpider scrapy genspider scrapy list scrapy genspider itcast “itcast.cn” scrapy crawl itcast -
Scrapy
2018-08-01 23:10:29Scrapy介绍 Scrapy一个开源和协作的框架,其最初是为了页面抓取(更确切来说,网络抓取)所设计的,使用它可以快速、简单、可扩展 的方式从网站中提取所需的数据。但目前Scrapy的用途十分广泛,可用于如挖掘、...Scrapy介绍
Scrapy一个开源和协作的框架,其最初是为了页面抓取(更确切来说,网络抓取)所设计的,使用它可以快速、简单、可扩展
的方式从网站中提取所需的数据。但目前Scrapy的用途十分广泛,可用于如挖掘、监测和自动化测试等领域,也可以应用在API
所返回的数据(例如Amazon Associates Web Services)或者通用的网络爬虫。
Scrapy是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架。因此Scrapy使用了一种非阻塞(又名异步)的代码来实现并发。整体架构大致如下
Scrapy数据流是由执行的核心引擎(engine)控制,流程是这样的:
1.引擎打开一个网站(open adomain),找到处理该网站的Spider并向该spider请求第一个要抓取的URL(s)。
2.引擎从Spider中获取到第一个要抓取的URL并在调度器(Scheduler)以Request调度。
3.引擎向调度器请求下一个要爬取的URL。
4.调度器返回下一个要抓取的URL给引擎,引擎将URL通过下载中间件(请求(request)方向)转发给下载器(Downloader).
5.一旦页面下载完毕,下载器生成一个该页面的Response,并将其通过下载中间件(返回(response)方向)发送给引擎。
6.引擎从下载器中接收到Response并通过Spider中间件(输入方向)发送给Spider处理。
7.Spider处理Response并返回爬取到的Item给Item Pipeline,将(Spider返回的)Request给调度器。
8.引擎将(Spider返回的)爬取的Item给Item Pipeline,将(Spider返回的)Request给调度器。
9.(从第二步)重复直到调度器中没有更多地request,引擎关闭该网站。
Scrapy主要包括了一下组件:
1.爬虫引擎(engine):爬虫引擎负责控制各个组件之间的数据流,当某些操作触发事件后都是通过engine来处理
2.调度器:调度接收来engine的请求并将请求请求放入队列中,并通过事件返回给engine
3.下载器:通过engine请求下载网络数据并将结果响应给engine
4.spider:Spider发出请求,并处理engine返回给它下载器响应数据,以items和规则内的数据请求(urls)返回给engine
5.管道数目(item pipeline):负责处理engine返回spider解析后的数据,并且将数据持久化,例如将数据存入数据库或者文件
6.下载中间件:下载中间件是engine和下载器交互组件,以钩子(插件)的形式存在,可以代替接收请求、处理数据的下载以及
将结果响应给engine
7.spider中间件:spider中间件是engine和spider之间的交互组件,以钩子(插件)的形式存在,可以代替处理response以及返回
给engine items及新的请求集
windows环境配置
Scrapy依赖包(也可到官网单独下载各文件安装):
1.lxml: pip install wheel
2.zope.interface:pip install zope.interface-4.3.3-cp35-cp35m-win_amd64.whl
3.pyOpenSSL:pip install pyOpenSSL
4.Twisted:pip install Twisted
5.Scrapy:pip install Scrapy
Anoconda+Pycharm+Scrapy Anaconda是包含了常用的数据科学库的Python发行版本,如果没有安装,
可以到http://www.continuum.io/downloads下载对应平台的包安装。如果已经安装,那么可以轻松地通过
conda命令安装Scrapy。conda install scrapy
Scrapy安装完成后,打开命令行终端输入scrapy,显示如下:
创建项目
- 创建爬虫项目命令
scrapy startproject project_name
- 创建爬虫文件命令
scrapy genspider example exameple.com
- 文件目录如下
D:\test>tree /F 卷 软件 的文件夹 PATH 列表 卷序列号为 58B6-0E53 D:. └─project_dir │ scrapy.cfg │ └─project_name │ items.py │ middlewares.py │ pipelines.py │ settings.py │ __init__.py │ ├─spiders │ │ __init__.py │ │ │ └─__pycache__ └─__pycache__
items.py:定义爬虫程序的数据模型,类似于实体类。
middlewares.py:爬虫中间件,负责调度。
pipelines.py:管道文件,负责对spider返回数据的处理。
spiders目录 负责存放继承自scrapy的爬虫类
scrapy.cfg.scrapy 基础配置
init:初始化文件
setting.py:负责对整个爬虫的配置,内容如下
# -*- coding: utf-8 -*- # Scrapy settings for baidu 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 = 'baidu' # 爬虫所在地 SPIDER_MODULES = ['baidu.spiders'] NEWSPIDER_MODULE = 'baidu.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'baidu (+http://www.yourdomain.com)' # Obey robots.txt rules # 遵守爬虫协议 ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) # 最大请求并发量 默认16 # CONCURRENT_REQUESTS = 32 # configure 配置 请求延迟 # 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) # 是否使用cookie #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 = { # 值越小,优先级越高,优先级越高,越先执行 # 'baidu.middlewares.BaiduSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 值越小,优先级越高,优先级越高,越先执行 # 'baidu.middlewares.BaiduDownloaderMiddleware': 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 = { # 值越小,优先级越高,优先级越高,越先执行 'baidu.pipelines.BaiduPipeline': 1, } # 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'
-
scrapy 常用命令详解
2020-06-07 18:14:26官方文档:https://docs.scrapy.org/en/latest/topics/commands.html Global commands: startproject genspider settings runspider shell fetch view version Project-...官方文档:https://docs.scrapy.org/en/latest/topics/commands.html
Global commands:
Project-only commands:
genspider-->注意:-t指定创建模板,默认basic
-
Syntax:
scrapy genspider [-t template] <name> <domain>
-
Requires project: no
Usage example:
$ scrapy genspider -l Available templates: basic crawl csvfeed xmlfeed $ scrapy genspider example example.com Created spider 'example' using template 'basic' $ scrapy genspider -t crawl scrapyorg scrapy.org Created spider 'scrapyorg' using template 'crawl'
runspider-->好处是无须项目路径支持,但spider_file.py不支持相对路径
-
Syntax:
scrapy runspider <spider_file.py>
-
Requires project: no
Run a spider self-contained in a Python file, without having to create a project.
Example usage:
$ scrapy runspider myspider.py [ ... spider starts crawling ... ]
parse-->重点推荐,调试方便,可指定回调函数运行 例如:scrapy parse https://www.baidu.com -c parse_detail --spider=tencent
-
Syntax:
scrapy parse <url> [options]
-
Requires project: yes
Fetches the given URL and parses it with the spider that handles it, using the method passed with the
--callback
option, orparse
if not given.Supported options:
-
--spider=SPIDER
: bypass spider autodetection and force use of specific spider -
--a NAME=VALUE
: set spider argument (may be repeated) -
--callback
or-c
: spider method to use as callback for parsing the response -
--meta
or-m
: additional request meta that will be passed to the callback request. This must be a valid json string. Example: –meta=’{“foo” : “bar”}’ -
--cbkwargs
: additional keyword arguments that will be passed to the callback. This must be a valid json string. Example: –cbkwargs=’{“foo” : “bar”}’ -
--pipelines
: process items through pipelines -
--rules
or-r
: useCrawlSpider
rules to discover the callback (i.e. spider method) to use for parsing the response -
--noitems
: don’t show scraped items -
--nolinks
: don’t show extracted links -
--nocolour
: avoid using pygments to colorize the output -
--depth
or-d
: depth level for which the requests should be followed recursively (default: 1) -
--verbose
or-v
: display information for each depth level
Usage example:
$ scrapy parse http://www.example.com/ -c parse_item [ ... scrapy log lines crawling example.com spider ... ] >>> STATUS DEPTH LEVEL 1 <<< # Scraped Items ------------------------------------------------------------ [{'name': 'Example item', 'category': 'Furniture', 'length': '12 cm'}] # Requests ----------------------------------------------------------------- []
-
-
scrapy-splash简单使用
2020-06-03 10:04:33scrapy-splash简单使用: 1.docker安装splash docker info 查看docker信息 docker images 查看所有镜像 docker pull scrapinghub/splash 安装scrapinghub/splash docker run -p 8050:8050 scrapinghub/splash &...scrapy-splash简单使用:
1.docker安装splash
docker info 查看docker信息
docker images 查看所有镜像
docker pull scrapinghub/splash 安装scrapinghub/splash
docker run -p 8050:8050 scrapinghub/splash & 指定8050端口运行2.pip install scrapy-splash
3.scrapy 配置:
SPLASH_URL = 'http://localhost:8050'
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'4.scrapy 使用
from scrapy_splash import SplashRequest
yield SplashRequest(self.start_urls[0], callback=self.parse, args={'wait': 0.5})测试代码:
import datetime import os import scrapy from scrapy_splash import SplashRequest from ..settings import LOG_DIR class SplashSpider(scrapy.Spider): name = 'splash' allowed_domains = ['biqugedu.com'] start_urls = ['http://www.biqugedu.com/0_25/'] custom_settings = { 'LOG_FILE': os.path.join(LOG_DIR, '%s_%s.log' % (name, datetime.date.today().strftime('%Y-%m-%d'))), 'LOG_LEVEL': 'INFO', 'CONCURRENT_REQUESTS': 8, 'AUTOTHROTTLE_ENABLED': True, 'AUTOTHROTTLE_TARGET_CONCURRENCY': 8, 'SPLASH_URL': 'http://localhost:8050', 'DOWNLOADER_MIDDLEWARES': { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, }, 'SPIDER_MIDDLEWARES': { 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, }, 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter', 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage', } def start_requests(self): yield SplashRequest(self.start_urls[0], callback=self.parse, args={'wait': 0.5}) def parse(self, response): """ :param response: :return: """ response_str = response.body.decode('utf-8', 'ignore') self.logger.info(response_str) self.logger.info(response_str.find('http://www.biqugedu.com/files/article/image/0/25/25s.jpg'))
scrapy-splash接收到js请求:
-
-
亲身经历——下载Scrapy
2020-08-25 22:51:56下载Scrapy Scrapy 是一套基于基于Twisted的异步处理框架,纯python实现的爬虫框架,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片等等。 首先 使用我们的pip命令对Scrapy进行... -
[Scrapy使用技巧] 如何在scrapy中捕获并处理各种异常
2018-06-15 16:29:50使用scrapy进行大型爬取任务的时候(爬取耗时以天为单位),无论主机网速多好,爬完之后总会发现scrapy日志中“item_scraped_count”不等于预先的种子数量,总有一部分种子爬取失败,失败的类型可能有如下图两种... -
Scrapy 学习
2020-12-29 18:00:29文章目录一、概述二、Scrapy五大基本构成:三、整体架构图四、Scrapy安装以及生成项目五、日志等级与日志保存六、导出为json或scv格式七、一个完整的案例 一、概述 Scrapy,Python开发的一个快速、高层次的屏幕抓取和... -
Python爬虫框架Scrapy
2019-08-07 15:57:44在Scrapy使用实践中,我们深刻体会到Scrapy框架只实现了爬虫流程,而真正的Scrapy核心是CSS选择器、xpath和正则表达式,所以本课程一开始先讲述了这三门课程,有了这三门课程的基础再学习Scrapy就会非常轻松。 -
Scrapy Shell
2019-12-18 23:47:46这篇文章很简单,可以说是 Scrapy 系列中最短最简单的文章。本篇文章主要讲解 Scrapy Shell 的相关知识。 零、 Scrapy Shell Scrapy Shell 是一个交互终端,可以在没有启动 Spider 的情况下调试代码。我们在开发爬虫... -
Python3 Scrapy爬虫框架(Scrapy/scrapy-redis)
2018-04-19 20:10:52Python3 Scrapy爬虫框架(Scrapy/scrapy-redis) 本文由 Luzhuo 编写,转发请保留该信息. 原文: https://blog.csdn.net/Rozol/article/details/80010173 Scrapy Scrapy 是 Python 写的, 主要用于爬取网站... -
Scrapy-Redis入门实战
2019-05-05 19:28:13目录 ...scrapy-redis是一个基于redis的scrapy组件,用于快速实现scrapy项目的分布式部署和数据爬取,其运行原理如下图所示。 Scrapy-Redis特性 分布式爬取 你可以启动多个共享同一redis队列... -
Scrapy 2.0
2020-03-25 11:04:49Scrapy 2.0 Scrapy 安装 (scrapy) C:\Users\15011>pip install scrapy -i https://pypi.douban.com/simple/ 如果遇到安装Twisted包的时候,报出以下错误。 Building wheels for collected packages: Twisted ... -
Scrapy入门
2020-04-12 22:06:58Scrapy入门 -
scrapy的使用
2018-10-16 16:25:36进入虚拟环境,pip install scrapy 2.创建新项目 执行:scrapy startproject Tencent , 会在当前目录下创建一个Tencent项目文件 3.创建爬虫 可手动创建 ,也可通过指令 : cd Tencent , scrapy crawl tencent ... -
Scrapy教程
2018-12-19 14:59:42Scrapy教程 Scrapy概述 Scrapy环境 Scrapy命令行工具 Scrapy蜘蛛 Scrapy选择器 Scrapy项目 Scrapy Item Loaders Scrapy shell Scrapy Item Pipeline Scrapy Feed exports Scrapy请求和响应 Scrapy链接提取器 ... -
scrapyd,scrapy部署
2020-03-31 08:07:43/Library/Frameworks/Python.framework/Versions/3.7/bin/scrapyd-deploy:23: ScrapyDeprecationWarning: Module scrapy.utils.http is deprecated, Please import from w3lib.http instead. from scrapy.utils.... -
记录一下scrapy中 settings 的一些配置
2020-01-16 11:49:41# 字符编码 FEED_EXPORT_ENCODING = 'utf-8' # redis写法一 # REDIS_URL = 'redis://localhost:6379' # redis写法二 REDIS_HOST = '192.168.10...# 默认的 scrapy redis 会读取下面的密码和db REDIS_PARAMS = {... -
Scrapy框架——安装Scrapy
2018-01-07 19:44:00Scrapy框架—— 安装Scrapy 需求配置 安装sqlite依赖库 编译python3.6 编译Twisted 安装Scrapy 测试Scrapy是否成功安装 Scrapy框架—— 安装Scrapy Scrapy 可以说是爬虫界鼎鼎有名的框架。 它是一个... -
Scrapy 入门教程
2020-11-21 13:45:12Scrapy 是用 Python 实现的一个为了爬取网站数据、提取结构性数据而编写的应用框架。 Scrapy 常应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。 通常我们可以很简单的通过 Scrapy 框架实现一个爬虫... -
[scrapy]scrapy-redis快速上手/scrapy爬虫分布式改造
2018-03-05 18:15:24了解scrapy,知道scrapy-redis可以用来干嘛,最好已经有了可以单机运行的scrapy爬虫。 已经尝试了一些反反爬措施后仍然觉得爬取效率太低。 已经看了无数scrapy-redis文章,却和我一样不得要领。(自己太笨) 已经看了... -
scrapy启动
2019-07-02 09:02:00在开始爬取之前,您必须创建一个新的Scrapy项目。 进入您打算存储代码的目录中,运行下列命令: scrapy startproject scrapytest 第一种scrapy genspider example example.com第二种scrapy genspider -t crawl ... -
scrapy实例
2018-08-30 20:21:31创建Scrapy项目 scrapy startproject Tencent 编写item import scrapy class TencentItem(scrapy.Item): # 职位名 positionname = scrapy.Field() # 详情连接 positionlink = scrapy.Field() # 职位类别... -
scrapy实战
2018-06-28 21:25:53scrapy实战 糗事百科 创建项目 scrapy startproject qiubaiproject cd qiubai scrapy genspider qsbk Item.py # -*- coding: utf-8 -*- import scrapy class QiubaiprojectItem(scrapy.Item): #...
-
基于STM32+W5500, 移植Ethernet文件并基于NTP实现RTC对时更新,USART可实现DMA 接收任意长度数据-C代码类资源
-
面试官常问:创建线程的几种方式
-
ContactManager.zip
-
30个生涯锦囊,带你跳出迷茫,找到适合你的职业方向
-
【数据分析-随到随学】Hive详解
-
云计算基础-Linux系统管理员
-
Swagger的参数说明显示不了或显示不完全的问题
-
背景
-
xiao4分析题背诵版.pdf
-
华为Mate20RS保时捷维修原理图PCB位置图(PDF格式)
-
插入排序
-
计算机网络基础(十四)---传输层-TCP的流量控制
-
WPF上位机数据采集与监控系统零基础实战
-
参照AUTOSAR标准的SmartOSEKOS4_0的设计与实现.caj
-
CAN的错误计数器
-
转行做IT-第7章 数组
-
快手如何修改定位直播同城位置添徵UFOBBA
-
XShell启动报错 “由于找不到mfc110.dll,无法继续执行代码“的解决方法
-
常用config
-
/etc/fstab文件中描述的文件系统也可以被卸载。