第1章 入门之scrapy快速一览

Scrapy是一个有着大量应用的可以用于爬取网站和提取结构化数据的程序框架,比如数据挖掘,信息处理。

虽然Scrapy最初设计用来做爬虫,但是它也可以通过API来提取结构化数据。

如何实现一个简单的爬虫

为了直观的了解scrapy,我们通过最简单的方法利用Scrapy Spider来实现一个爬虫。

首先我们编写一个用于爬取国外著名的类似知乎的网站 http://quotes.toscrape.com作为示例,以下是相关代码:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = 'quotes'
    start_urls = [
        'http://quotes.toscrape.com/tag/humor/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
    
    
                'author': quote.xpath('span/small/text()').get(),
                'text': quote.css('span.text::text').get(),
            }

        next_page = response.css('li.next a::attr("href")').get()
        if next_page is not None:
            yield response.follow(next_page, self.parse)

这里我推荐使用JetBrains推出的PyCharm作为开发工具。具体怎么新建项目就不介绍了,因为专栏主要专注scrapy框架。如图:

爬虫代码片段
如果使用的是PyCharm可以直接运行,运行之后发现没反应。我们可以使用命令行来运行一下试试,假设这段代码已经保存为demo.py文件,接下来我们使用scrapy的runspider命令来试试:

scrapy runspider demo.py -o quotes.json

当这个命令完成后,你会发现demo.py的相同目录下多了一个quotes.json的文件,包含text和author字段,执行命令的截图如下:

命令运行截图
文件的内容格式如下:

[
{"author": "Jane Austen", "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"},
{"author": "Steve Martin", "text": "\u201cA day without sunshine is like, you know, night.\u201d"},
{"author": "Garrison Keillor", "text": "\u201cAnyone who thinks sitting in church can make you a Christian must also think that sitting in a garage can make you a car.\u201d"},
{"author": "Jim Henson", "text": "\u201cBeauty is in the eye of the beholder and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.\u201d"},
{"author": "Charles M. Schulz", "text": "\u201cAll you need is love. But a little chocolate now and then doesn't hurt.\u201d"},
{"author": "Suzanne Collins", "text": "\u201cRemember, we're madly in love, so it's all right to kiss me anytime you feel like it.\u201d"},
{"author": "Charles Bukowski", "text": "\u201cSome people never go crazy. What truly horrible lives they must lead.\u201d"},
{"author": "Terry Pratchett", "text": "\u201cThe trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.\u201d"},
{"author": "Dr. Seuss", "text": "\u201cThink left and think right and think low and think high. Oh, the thinks you can think up if only you try!\u201d"},
{"author": "George Carlin", "text": "\u201cThe reason I talk to myself is because I\u2019m the only one whose answers I accept.\u201d"},
{"author": "W.C. Fields", "text": "\u201cI am free of all prejudice. I hate everyone equally. \u201d"},
{"author": "Jane Austen", "text": "\u201cA lady's imagination is very rapid; it jumps from admiration to love, from love to matrimony in a moment.\u201d"}
]

爬虫执行的过程

当你运行scrapy runspider demo.py -o quotes.json命令的时候,Scrapy根据爬虫的定义通过爬虫引擎运行。

爬虫首先从start_urls属性中的URL进行请求,并且调用默认的回调方法parse,将response对象当成一个参数传递进去。在parse回调中,我们使用一个CSS样式进行遍历,同是Python字典提取提问的text和author字段,接下来寻找下一页的链接,并生成另外一个请求调用parse方法作为回调。

这样我们就了解到了一个特点,Scrapy框架的请求是定时的,而且是异步处理。这就意味着Scrapy在执行任务时不需要等待一个请求完成,甚至是处理完成,它可以同事发起另外一个请求或者做其他事情。这就意味着,及时有些请求失败或者发生错误,其他的请求不妨碍执行。

除了能够并发处理请求之外,Scrapy也允许你对爬虫进行一些设置,比如下载延迟,限制每个域名或者IP的并发请求数量。甚至能自动的进行配置。

Scrapy还有哪些强大的功能

上面简单的介绍了Scrapy如何从一个网站解析和存储指定的字段,但这仅仅是Scrapy的冰山一角。Scrapy提供了大量的强大的特性来让爬虫更加容易和高效。比如:

  • 内建的对HTML/XML数据解析的支持
  • 交互式shell(IPython aware),在编写和调试爬虫时非常有用
  • 内建的支持多种格式(Json,csv,XML)的支持以及在FTP或者本地等进行存储
  • 强大的扩展支持(中间件,扩展,管道)
  • 大量内置的扩展和中间件用于处理以下内容
    – cookies和session处理
    – HTTP中的压缩,认证,缓存等
    – user-agent的伪造
    – robots.txt
    – 爬虫约束
    – 等等
  • 一个Telnet的控制台,用于爬虫调试
    等等等等。。。。

编写运行爬虫推荐买一个便宜的服务器,这里推荐华为云,扫码可以快速的进行注册:
华为云服务
限时打折。

猜你喜欢

转载自blog.csdn.net/song19891121/article/details/104686533