您的位置:首页 > 其它

1、初识scrapy

2017-04-24 14:32 190 查看
Scrapy是一个从网上爬取数据的开源的、友好的框架。

An open source and collaborative framework for extracting the data from website.

scrapy具有以下优点:

1. 快速强大

2. 容易扩展

3. 适应于多平台

一个简单的爬虫

下面这个爬虫爬取了stackoverflow问题页中的内容。

stackoverflow_spider.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 result.csv
,将爬虫爬取结果保存到result.csv中。

该爬虫的运行过程:

1. 使用start_urls作为初始url生成Request,并默认把parse作为它的回调函数。

2. 在parse中采用css选择器获得目标URL,并注册parse_question作为目标URL的回调函数。

scrapy的高级特性

内置css/xpath/re数据抽取器

交互式控制台用于调试数据抽取方法(scrapy shell)

内置对爬取结果的输出支持,可以将结果保存为json/csv/xml等

自动处理编码

支持自定义扩展

丰富的内置扩展,可用于处理:

cookies and session

http features like compression, authentication,caching

user-agent spoofing

robots.txt

crawl depth restriction
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  爬虫