Scrapy一个开源和协做的框架,其最初是为了页面抓取 (更确切来讲, 网络抓取 )所设计的,使用它能够以快速、简单、可扩展的方式从网站中提取所需的数据。但目前Scrapy的用途十分普遍,可用于如数据挖掘、监测和自动化测试等领域,也能够应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架。所以Scrapy使用了一种非阻塞(又名异步)的代码来实现并发。css
总体架构大体以下:html
''' Components: 一、引擎(EGINE) 引擎负责控制系统全部组件之间的数据流,并在某些动做发生时触发事件。有关详细信息,请参见上面的数据流部分。 二、调度器(SCHEDULER) 用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 能够想像成一个URL的优先级队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址
三、下载器(DOWLOADER) 用于下载网页内容, 并将网页内容返回给EGINE,下载器是创建在twisted这个高效的异步模型上的
四、爬虫(SPIDERS) SPIDERS是开发人员自定义的类,用来解析responses,而且提取items,或者发送新的请求
五、项目管道(ITEM PIPLINES) 在items被提取后负责处理它们,主要包括清理、验证、持久化(好比存到数据库)等操做 下载器中间件(Downloader Middlewares)位于Scrapy引擎和下载器之间,主要用来处理从EGINE传到DOWLOADER的请求request,已经从DOWNLOADER传到EGINE的响应response,
你可用该中间件作如下几件事: (1) process a request just before it is sent to the Downloader (i.e. right before Scrapy sends the request to the website); (2) change received response before passing it to a spider; (3) send a new Request instead of passing received response to a spider; (4) pass response to a spider without fetching a web page; (5) silently drop some requests.
六、爬虫中间件(Spider Middlewares) 位于EGINE和SPIDERS之间,主要工做是处理SPIDERS的输入(即responses)和输出(即requests) '''
官网连接python
#Windows平台 一、pip3 install wheel #安装后,便支持经过wheel文件安装软件,wheel文件官网:https://www.lfd.uci.edu/~gohlke/pythonlibs 3、pip3 install lxml 4、pip3 install pyopenssl 五、下载并安装pywin32:https://sourceforge.net/projects/pywin32/files/pywin32/ 六、下载twisted的wheel文件:http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted 七、执行pip3 install 下载目录\Twisted-17.9.0-cp36-cp36m-win_amd64.whl 8、pip3 install scrapy #Linux平台 一、pip3 install scrapy
# 1 查看帮助 scrapy -h scrapy <command> -h # 2 有两种命令:其中Project-only必须切到项目文件夹下才能执行,而Global的命令则不须要 Global commands: startproject #建立项目 genspider #建立爬虫程序 settings #若是是在项目目录下,则获得的是该项目的配置 runspider #运行一个独立的python文件,没必要建立项目 shell #scrapy shell url地址 在交互式调试,如选择器规则正确与否 fetch #独立于程单纯地爬取一个页面,能够拿到请求头 view #下载完毕后直接弹出浏览器,以此能够分辨出哪些数据是ajax请求 version #scrapy version 查看scrapy的版本,scrapy version -v查看scrapy依赖库的版本 Project-only commands: crawl #运行爬虫,必须建立项目才行,确保配置文件中ROBOTSTXT_OBEY = False check #检测项目中有无语法错误 list #列出项目中所包含的爬虫名 edit #编辑器,通常不用 parse #scrapy parse url地址 --callback 回调函数 #以此能够验证咱们的回调函数是否正确 bench #scrapy bentch压力测试 # 3 官网连接 https://docs.scrapy.org/en/latest/topics/commands.html
''' project_name/ scrapy.cfg project_name/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py 爬虫1.py 爬虫2.py 爬虫3.py '''
文件说明:web
注意:ajax
一、通常建立爬虫文件时,以网站域名命名shell
二、默认只能在终端执行命令,为了更便捷操做:数据库
#在项目根目录下新建:entrypoint.py from scrapy.cmdline import execute execute(['scrapy', 'crawl', 'xiaohua'])
框架基础:spider类,选择器,浏览器
Spiders是定义如何抓取某个站点(或一组站点)的类,包括如何执行爬行(即跟随连接)以及如何从其页面中提取结构化数据(即抓取项目)。换句话说,Spiders是您为特定站点(或者在某些状况下,一组站点)爬网和解析页面定义自定义行为的地方。 服务器
Spiders会循环作以下事情:网络
''' 一、 生成初始的Requests来爬取第一个URLS,而且标识一个回调函数 第一个请求定义在start_requests()方法内默认从start_urls列表中得到url地址来生成Request请求,
默认的回调函数是parse方法。回调函数在下载完成返回response时自动触发 二、 在回调函数中,解析response而且返回值 返回值能够4种: 包含解析数据的字典 Item对象 新的Request对象(新的Requests也须要指定一个回调函数) 或者是可迭代对象(包含Items或Request) 三、在回调函数中解析页面内容 一般使用Scrapy自带的Selectors,但很明显你也可使用Beutifulsoup,lxml或其余你爱用啥用啥。 四、最后,针对返回的Items对象将会被持久化到数据库 经过Item Pipeline组件存到数据库:https://docs.scrapy.org/en/latest/topics/item-pipeline.html#topics-item-pipeline) 或者导出到不一样的文件(经过Feed exports:https://docs.scrapy.org/en/latest/topics/feed-exports.html#topics-feed-exports) '''
为了解释如何使用选择器,咱们将使用Scrapy shell(提供交互式测试)和Scrapy文档服务器中的示例页面,
这是它的HTML代码:
<html> <head> <base href='http://example.com/' /> <title>Example website</title> </head> <body> <div id='images'> <a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a> <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a> <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a> <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a> <a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a> </div> </body> </html>
首先,让咱们打开shell:
scrapy shell https://doc.scrapy.org/en/latest/_static/selectors-sample1.html
而后,在shell加载以后,您将得到响应做为response
shell变量,并在response.selector
属性中附加选择器。
让咱们构建一个XPath来选择title标签内的文本:
>>> response.selector.xpath('//title/text()') [<Selector (text) xpath=//title/text()>]
使用XPath和CSS查询响应很是常见,响应包括两个便捷快捷方式:response.xpath()
和response.css()
:
>>> response.xpath('//title/text()') [<Selector (text) xpath=//title/text()>] >>> response.css('title::text') [<Selector (text) xpath=//title/text()>]
正如你所看到的,.xpath()
而且.css()
方法返回一个 SelectorList
实例,这是新的选择列表。此API可用于快速选择嵌套数据:
>>> response.css('img').xpath('@src').extract() [u'image1_thumb.jpg', u'image2_thumb.jpg', u'image3_thumb.jpg', u'image4_thumb.jpg', u'image5_thumb.jpg']
要实际提取文本数据,必须调用selector .extract()
方法,以下所示:
>>> response.xpath('//title/text()').extract() [u'Example website']
若是只想提取第一个匹配的元素,能够调用选择器 .extract_first()
>>> response.xpath('//div[@id="images"]/a/text()').extract_first() u'Name: My image 1 '
如今咱们将得到基本URL和一些图像连接:
>>> response.xpath('//base/@href').extract() [u'http://example.com/'] >>> response.css('base::attr(href)').extract() [u'http://example.com/'] >>> response.xpath('//a[contains(@href, "image")]/@href').extract() [u'image1.html', u'image2.html', u'image3.html', u'image4.html', u'image5.html'] >>> response.css('a[href*=image]::attr(href)').extract() [u'image1.html', u'image2.html', u'image3.html', u'image4.html', u'image5.html'] >>> response.xpath('//a[contains(@href, "image")]/img/@src').extract() [u'image1_thumb.jpg', u'image2_thumb.jpg', u'image3_thumb.jpg', u'image4_thumb.jpg', u'image5_thumb.jpg'] >>> response.css('a[href*=image] img::attr(src)').extract() [u'image1_thumb.jpg', u'image2_thumb.jpg', u'image3_thumb.jpg', u'image4_thumb.jpg', u'image5_thumb.jpg']