当前位置:嗨网首页>书籍在线阅读

08-检查结果

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

[toc]

8.4.1 检查结果

下面是该爬虫的完整代码。

class CountryOrDistrictSpider(CrawlSpider):
    name = 'country_or_district'
    start_urls = ['http://example.python-scraping.com/']
    allowed_domains = ['example.python-scraping.com']
    rules = (
        Rule(LinkExtractor(allow=r'/index/', deny=r'/user/'), follow=True),
        Rule(LinkExtractor(allow=r'/view/', deny=r'/user/'),
callback='parse_item')
    )
    def parse_item(self, response):
        item = CountryOrDistrictItem()
        name_css = 'tr#places_country_or_district__row td.w2p_fw::text'
        item['name'] = response.css(name_css).extract()
        pop_xpath =
'//tr[@id="places_population__row"]/td[@class="w2p_fw"]/text()'
        item['population'] = response.xpath(pop_xpath).extract()
        return item

要想保存结果,我们可以定义管道,或在我们的 settings.py 文件中配置输出设置。不过,Scrapy还提供了一个更方便的 --output 选项,用于自动保存已抓取的条目,其可选格式包括CSV、JSON和XML。

下面是该爬虫的最终版运行时的结果,它将会输出到一个CSV文件中,此外该爬虫的日志级别被设定为 INFO 以过滤不重要的信息。

$ scrapy crawl country_or_district --output=../../../data/scrapy_countries_ or_districts.csv -s
LOG_LEVEL=INFO
2017-03-24 14:20:25 [scrapy.extensions.logstats] INFO: Crawled 277 pages
(at 10 pages/min), scraped 249 items (at 9 items/min)
2017-03-24 14:20:42 [scrapy.core.engine] INFO: Closing spider (finished)
2017-03-24 14:20:42 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 158580,
 'downloader/request_count': 280,
 'downloader/request_method_count/GET': 280,
 'downloader/response_bytes': 944210,
 'downloader/response_count': 280,
 'downloader/response_status_count/200': 280,
 'dupefilter/filtered': 61,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 3, 24, 13, 20, 42, 792220),
 'item_scraped_count': 252,
 'log_count/INFO': 35,
 'request_depth_max': 26,
 'response_received_count': 280,
 'scheduler/dequeued': 279,
 'scheduler/dequeued/memory': 279,
 'scheduler/enqueued': 279,
 'scheduler/enqueued/memory': 279,
 'start_time': datetime.datetime(2017, 3, 24, 12, 52, 25, 733163)}
2017-03-24 14:20:42 [scrapy.core.engine] INFO: Spider closed (finished)

在爬取过程的最后阶段,Scrapy会输出一些统计信息,给出爬虫运行的一些指标。从统计结果中,我们可以了解到爬虫总共爬取了280个网页,并抓取到其中的252个条目,这与数据库中的国家(或地区)数量一致,因此我们知道爬虫已经找到了所有的国家(或地区)数据。

你需要从Scrapy创建时生成的目录中运行Scrapy的spider和crawl命令(对于我们的项目来说是使用 `startproject` 命令创建的 `example/` 目录)。爬虫使用 `scrapy.cfg` 以及 `settings.py` 文件来确定如何抓取以及抓取什么地方,并设置用于爬取或抓取的爬虫路径。

要想验证抓取的这些国家(或地区)信息正确与否,我们可以检查 countries_or_districts.csv 文件中的内容。

name,population
Afghanistan,"29,121,286"
Antigua and Barbuda,"86,754"
Antarctica,0
Anguilla,"13,254"
Angola,"13,068,161"
Andorra,"84,000"
American Samoa,"57,881"
Algeria,"34,586,184"
Albania,"2,986,952"
Aland Islands,"26,711"
...

和预期一样,CSV文件中包含了每个国家(或地区)的名称和人口数量。抓取这些数据所要编写的代码比第2章中的原始爬虫要少很多,这是因为Scrapy提供了一些高级功能以及很好用的内置功能,比如内置的CSV写入功能。

在8.5节中,我们将使用Portia重新实现该爬虫,而且要编写的代码会更少。