1、初识scrapy

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容