爬虫:Scrapy笔记- 入门篇
Scrapy笔记01- 入门篇
Scrapy是一个为了爬取网站资料,提取结构性资料而编写的应用框架。可以应用在包括资料探勘, 资讯处理或储存历史资料等一系列的程式中。其最初是为了页面抓取(更确切来说,网络抓取)所设计的, 也可以应用在获取API所返回的资料(比如Web Services)或者通用的网络爬虫。Scrapy也能帮你实现高阶的爬虫框架,比如爬取时的网站认证、内容的分析处理、重复抓取、分散式爬取等等很复杂的事。
安装scrapy
我的测试环境是centos6.5
升级python到最新版的2.7,下面的所有步骤都切换到root使用者
由于scrapy目前只能执行在python2上,所以先更新centos上面的python到最新的 Python 2.7.11, 具体方法请google下很多这样的教程。
先安装一些依赖软件
yum install python-devel
yum install libffi-devel
yum install openssl-devel
然后安装pyopenssl库
pip install pyopenssl
安装xlml
yum install python-lxml
yum install libxml2-devel
yum install libxslt-devel
安装service-identity
pip install service-identity
安装twisted
pip install scrapy
安装scrapy
pip install scrapy -U
测试scrapy
scrapy bench
最终成功,太不容易了!
简单示例
建立一个python原始档,名为stackoverflow.py,内容如下:
import scrapy
class StackOverflowSpider(scrapy.Spider):
name = 'stackoverflow'
start_urls = ['http://stackoverflow.com/questions?sort=votes']
def parse(self, response):
for href in response.css('.question-summary h3 a::attr(href)'):
full_url = response.urljoin(href.extract())
yield scrapy.Request(full_url, callback=self.parse_question)
def parse_question(self, response):
yield {
'title': response.css('h1 a::text').extract()[0],
'votes': response.css('.question .vote-count-post::text').extract()[0],
'body': response.css('.question .post-text').extract()[0],
'tags': response.css('.question .post-tag::text').extract(),
'link': response.url,
}
执行:
scrapy runspider stackoverflow_spider.py -o top-stackoverflow-questions.json
结果类似下面:
[{
"body": "... LONG HTML HERE ...",
"link": "http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array",
"tags": ["java", "c++", "performance", "optimization"],
"title": "Why is processing a sorted array faster than an unsorted array?",
"votes": "9924"
},
{
"body": "... LONG HTML HERE ...",
"link": "http://stackoverflow.com/questions/1260748/how-do-i-remove-a-git-submodule",
"tags": ["git", "git-submodules"],
"title": "How do I remove a Git submodule?",
"votes": "1764"
},
...]
当你执行scrapy runspider somefile.py这条语句的时候,Scrapy会去寻找原始档中定义的一个spider并且交给爬虫引擎来执行它。 start_urls属性定义了开始的URL,爬虫会通过它来构建初始的请求,返回response后再呼叫预设的回拨方法parse并传入这个response。 我们在parse回拨方法中通过使用css选择器提取每个提问页面连结的href属性值,然后yield另外一个请求, 并注册parse_question回拨方法,在这个请求完成后被执行。
处理流程图:

Scrapy的一个好处是所有请求都是被排程并异步处理,就算某个请求出错也不影响其他请求继续被处理。
我们的示例中将解析结果生成json格式,你还可以汇出为其他格式(比如XML、CSV),或者是将其储存到FTP、Amazon S3上。 你还可以通过pipeline 将它们储存到数据库中去,这些资料储存的方式各种各样。
Scrapy特性一览
你已经可以通过Scrapy从一个网站上面爬取资料并将其解析储存下来了,但是这只是Scrapy的皮毛。 Scrapy提供了更多的特性来让你爬取更加容易和高效。比如:
内建支援扩充套件的CSS选择器和XPath表示式来从HTML/XML源代码中选择并提取资料,还能使用正则表示式提供互动式shell控制台试验CSS和XPath表示式,这个在除错你的蜘蛛程式时很有用内建支援生成多种格式的订阅汇出(JSON、CSV、XML)并将它们储存在多个位置(FTP、S3、本地档案系统)健壮的编码支援和自动识别,用于处理外文、非标准和错误编码问题可扩充套件,允许你使用signals 和友好的API(middlewares, extensions, 和pipelines)来编写自定义外挂功能。大量的内建扩充套件和中介软件供使用:cookies and session handlingHTTP features like compression, authentication, cachinguser-agent spoofingrobots.txtcrawl depth restrictionand more还有其他好多好东东,比如可重复利用蜘蛛来爬取Sitemaps和XML/CSV订阅, 一个跟爬取元素关联的媒体管道来 自动下载图片, 一个快取DNS解析器等等。