手把手教你写网络爬虫(4):Scrapy入门

开发 后端
本文介绍Scrapy的架构,包括组件以及在系统中发生的数据流的概览(红色箭头所示)。 之后会对每个组件做简单介绍,数据流也会做一个简要描述。

本系列:

上期我们理性的分析了为什么要学习Scrapy,理由只有一个,那就是免费,一分钱都不用花!

咦?怎么有人扔西红柿?好吧,我承认电视看多了。不过今天是没得看了,为了赶稿,又是一个不眠夜。。。言归正传,我们将在这一期介绍完Scrapy的基础知识, 如果想深入研究,大家可以参考官方文档,那可是出了名的全面,我就不占用公众号的篇幅了。

[[229476]]

架构简介

下面是Scrapy的架构,包括组件以及在系统中发生的数据流的概览(红色箭头所示)。 之后会对每个组件做简单介绍,数据流也会做一个简要描述。

架构就是这样,流程和我第二篇里介绍的迷你架构差不多,但扩展性非常强大。

One more thing

[[229477]]

 

  1. scrapy startproject tutorial 

该命令将会创建包含下列内容的 tutorial 目录:

 

  1. tutorial/  
  2.     scrapy.cfg            # 项目的配置文件  
  3.     tutorial/             # 该项目的python模块。之后您将在此加入代码  
  4.         __init__.py  
  5.         items.py          # 项目中的item文件  
  6.         pipelines.py      # 项目中的pipelines文件  
  7.         settings.py       # 项目的设置文件  
  8.         spiders/          # 放置spider代码的目录  
  9.             __init__.py 

编写***个爬虫

Spider是用户编写用于从单个网站(或者一些网站)爬取数据的类。其包含了一个用于下载的初始URL,以及如何跟进网页中的链接以及如何分析页面中的内容的方法。

以下为我们的***个Spider代码,保存在 tutorial/spiders 目录下的 quotes_spider.py文件中:

 

  1. import scrapy   
  2.  
  3. class QuotesSpider(scrapy.Spider):  
  4.     name = "quotes"   
  5.  
  6.     def start_requests(self):  
  7.         urls = [  
  8.             'http://quotes.toscrape.com/page/1/' 
  9.             'http://quotes.toscrape.com/page/2/' 
  10.         ]  
  11.         for url in urls:  
  12.             yield scrapy.Request(url=url, callback=self.parse)   
  13.  
  14.     def parse(self, response):  
  15.         page = response.url.split("/")[-2]  
  16.         filename = 'quotes-%s.html' % page  
  17.         with open(filename, 'wb'as f:  
  18.             f.write(response.body)  
  19.         self.log('Saved file %s' % filename) 

运行我们的爬虫

进入项目的根目录,执行下列命令启动spider:

 

  1. scrapy crawl quotes 

这个命令启动用于爬取 quotes.toscrape.com 的spider,你将得到类似的输出:

 

  1. 2017-05-10 20:36:17 [scrapy.core.engine] INFO: Spider opened  
  2. 2017-05-10 20:36:17 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min 
  3. 2017-05-10 20:36:17 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023  
  4. 2017-05-10 20:36:17 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)  
  5. 2017-05-10 20:36:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None)  
  6. 2017-05-10 20:36:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/2/> (referer: None)  
  7. 2017-05-10 20:36:17 [quotes] DEBUG: Saved file quotes-1.html  
  8. 2017-05-10 20:36:17 [quotes] DEBUG: Saved file quotes-2.html  
  9. 2017-05-10 20:36:17 [scrapy.core.engine] INFO: Closing spider (finished) 

提取数据

我们之前只是保存了HTML页面,并没有提取数据。现在升级一下代码,把提取功能加进去。至于如何使用浏览器的开发者模式分析网页,之前已经介绍过了。

 

  1. import scrapy   
  2. class QuotesSpider(scrapy.Spider):  
  3.     name = "quotes"  
  4.     start_urls = [  
  5.         'http://quotes.toscrape.com/page/1/' 
  6.         'http://quotes.toscrape.com/page/2/' 
  7.     ]   
  8.  
  9.     def parse(self, response):  
  10.         for quote in response.css('div.quote'):  
  11.             yield {  
  12.                 'text': quote.css('span.text::text').extract_first(),  
  13.                 'author': quote.css('small.author::text').extract_first(),  
  14.                 'tags': quote.css('div.tags a.tag::text').extract(),  
  15.             } 

再次运行这个爬虫,你将在日志里看到被提取出的数据:

 

  1. 2017-05-10 20:38:33 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/>  
  2. {'tags': ['life''love'], 'author''André Gide''text''“It is better to be hated for what you are than to be loved for what you are not.”' 
  3. 2017-05-10 20:38:33 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/>  
  4. {'tags': ['edison''failure''inspirational''paraphrased'], 'author''Thomas A. Edison''text'"“I have not failed. I've just found 10,000 ways that won't work.”"

保存爬取的数据

最简单存储爬取的数据的方式是使用 Feed exports:

 

  1. scrapy crawl quotes -o quotes.json 

该命令将采用 JSON 格式对爬取的数据进行序列化,生成quotes.json文件。

 

在类似本篇教程里这样小规模的项目中,这种存储方式已经足够。如果需要对爬取到的item做更多更为复杂的操作,你可以编写 Item Pipeline,tutorial/pipelines.py在最开始的时候已经自动创建了。 

责任编辑:庞桂玉 来源: Python开发者
相关推荐

2018-05-16 15:46:06

Python网络爬虫PhantomJS

2018-05-14 16:34:08

Python网络爬虫Scrapy

2021-01-30 10:37:18

ScrapyGerapy网络爬虫

2018-05-14 15:27:06

Python网络爬虫爬虫架构

2018-05-22 15:30:30

Python网络爬虫分布式爬虫

2018-05-22 16:28:46

Python网络爬虫URL去重

2018-05-14 14:02:41

Python爬虫网易云音乐

2020-07-10 08:24:18

Python开发工具

2023-03-27 08:28:57

spring代码,starter

2021-07-14 09:00:00

JavaFX开发应用

2021-06-29 12:27:19

Spring BootCAS 登录

2021-11-09 09:01:36

Python网络爬虫Python基础

2021-04-01 09:02:38

Python小说下载网络爬虫

2011-01-10 14:41:26

2011-05-03 15:59:00

黑盒打印机

2022-03-08 11:17:54

函数指针回调函数C语言

2023-04-26 12:46:43

DockerSpringKubernetes

2022-03-14 14:47:21

HarmonyOS操作系统鸿蒙

2022-01-08 20:04:20

拦截系统调用

2022-07-27 08:16:22

搜索引擎Lucene
点赞
收藏

51CTO技术栈公众号