Scrapy基础——Debug和test

简介: 写代码的最常做的事情就是debug和test,那么如何在Scrapy中检查爬虫能否正常运行,保证在大规模作业时不会遇到奇奇怪怪的问题呢?这里主要根据实例说些debug的方法。

写代码的最常做的事情就是debug和test,那么如何在Scrapy中检查爬虫能否正常运行,保证在大规模作业时不会遇到奇奇怪怪的问题呢?这里主要根据实例说些debug的方法。


Debug三部曲

Parse

parse命令主要用于从method级别去检查爬虫不同部分的行为。它有以下几个可选项:

  • --spider=SPIDER,指定爬虫
  • --a NAME=VALUE,设置爬虫变量
  • --callback/-c 指定爬取响应的爬虫方法
  • --pipelines: 通过pipelines处理爬取的item
  • --rules,使用CrawlSpider的时候用于定义规则
  • --noitems,不要显示爬取后的items
  • --nolinks,,不要显示提取的链接(links)
  • --nocolor, 不要颜色
  • --depth/-d,对于每个链接的爬取深度,类似于盗梦空间的梦中梦,默认是1,就是爬取这个链接中网页后就停止
  • --verbose/-v,相当于显示每一层的梦境内容
    举个栗子,下面是我用来爬取豆瓣哲学分类下所有图书信息的代码,
# -*- coding: utf-8 -*-
from scrapy.spiders import CrawlSpider, Rule
from scrapy.http import Request
from ..items import DoubanItem
from scrapy.linkextractors import LinkExtractor


class DoubanSpider(CrawlSpider):
    name = "douban"
    allowed_domains = ["douban.com"]
    start_urls = (
        'https://book.douban.com/tag/哲学',
    )

    rules = (
        Rule(LinkExtractor(allow='/tag/哲学',restrict_xpaths=('//*[@id="subject_list"]/div[2]/span/a')),
            callback='link_parse',follow=True),

    )

    def link_parse(self, response):
        links = response.css('div.info > h2 > a::attr(href)').extract()
        for link in links:
            yield Request(link,callback=self.parse_content)

    def parse_content(self, response):
        item = DoubanItem()
        item['title'] = response.xpath('//*[@id="wrapper"]/h1/span/text()').extract()
        item['author'] = response.css('div#info > span >a::text').extract_first()
        # item['pub_date'] = response.xpath('//*[@id="info"]/text()[4]').extract()
        # item['price'] =response.xpath('//*[@id="info"]/text()[6]').extract()
        item['desc'] = response.xpath('//*[@id="link-report"]/div[1]/div/p').extract_first() or \
                        response.xpath('//*[@id="link-report"]/span[1]/div/p').extract_first()
        item['score'] = response.xpath('//*[@id="interest_sectl"]/div/div[2]/strong/text()').extract_first()
        return item

我想测试一下方法parse_content获取link_parse爬取到每本书的链接后能不能到继续爬取链接里面的图书信息,在命令中输入scrapy parse --spider=douban -c parse_content -v https://book.douban.com/subject/1291204/
命令说明:指定使用爬虫douban的parse_content方法去爬取链接,并且显示每一层的内容,结果如下:

img_85948735cb737fcf307775b95b760246.png

所以他可以验证你定义爬虫的方法能否正常使用哦。

Scrapy Shell

parse只能显示爬取的结果,但是爬虫爬取的细节就是一个黑箱子,你无法看见。这里我们就可以使用前面常用shell,不过功能更具体一点。
你可以使用scrapy shell --spider=douban https://book.douban.com/tag/哲学,然后在之后的命令行中使用xpath和css选择器提取item,使用view(reponse)就能以你定义的爬虫的视角看网页。

Logging

这个很像我们刚开始最爱用的print,在快要出错的地方放在一行print看看案发现场。这里我们快要使用它自带的记录函数logging,也是在容易出错的地方加一行这个,如下图

img_d69ff922fc15af428e32a15d31a063f1.png
logging

test之Spiders Contracts

我在爬取某图片网站的时候,打算先爬取个50个页面测试一个爬虫的稳定性,你可以选择瞪着显示器,一个一个数,看结果不断的闪过然后觉得差不多了退出。随意推荐使用Scrapy中的一个用来进行单元测试的特性--Contract,顾名思义这是一个合同工,合同到期就停止工作。直接上代码说他的使用方法:

img_86f8d854068c892b2df3f7f520ad7221.png
contract

只要在你需要测试的单元用 """ code """,在code中添加红框里的内容,'#'这个字段及其后面内容不需要添加,我这里用于说明功能而已。使用 scrapy check <spider>既可以进行单元测试,如果你需要测试更多内容,请翻阅 这里
运行结果如下,看来我要去处理一下错误了。

img_1d2848c346c792b2488013bd3769b52d.png
check结果

以上就是scrapy常用的debug和test技巧,能够帮助你验证爬虫写的一个功能能否正常运行,出错的时候去检查网页,记录错误信息。当然no news is good news,还是祝大家能够顺利的写好代码。
你也可以在我的个人博客上看到这篇文章,虽然没有什么差别。

目录
相关文章
|
7月前
|
数据可视化 Python
常见的bug---5、在安装superset时候报错,Command “python setup.py egg_info“ failed with error code 1
常见的bug---5、在安装superset时候报错,Command “python setup.py egg_info“ failed with error code 1
|
8月前
|
Python
PyCharm在用Django开发时debug模式启动失败显示can&#39;t find &#39;__main__&#39; module的解决方法
初次用Django开发web应用,在试图用Pycharm进行debug的时候,出现了一个奇怪的问题。以正常模式启动或者在terminal启动都没有问题。但是以debug模式启动时,显示`can&#39;t find &#39;__main__&#39; module”`报错。在网上找了很久都没有看到解决方法,最后在某乎上看到一篇文章,在启动时加上`--noreload`参数,既可以debug模式启动。
109 0
|
4月前
|
开发者 Python
Python学习 -- logging模块
Python学习 -- logging模块
20 0
|
9月前
|
Python
python-- logging 模块
python-- logging 模块
|
API Python
Python 日志打印之logging.config.dictConfig使用总结
Python 日志打印之logging.config.dictConfig使用总结
130 0
|
测试技术
pytest学习和使用22-allure特性 丨总览中的Environment、Categories设置以及Flaky test使用
pytest学习和使用22-allure特性 丨总览中的Environment、Categories设置以及Flaky test使用
105 0
|
测试技术
基于UIAutomation+Python+Unittest+Beautifulreport的WindowsGUI自动化测试框架主入口main解析
基于UIAutomation+Python+Unittest+Beautifulreport的WindowsGUI自动化测试框架主入口main解析
160 0
|
机器学习/深度学习 Python
【错误记录】PyCharm 运行 Python 程序报错 ( PEP 8: E402 module level import not at top of file )
【错误记录】PyCharm 运行 Python 程序报错 ( PEP 8: E402 module level import not at top of file )
2942 0
【错误记录】PyCharm 运行 Python 程序报错 ( PEP 8: E402 module level import not at top of file )
安装 xgboost 报错ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/fold
安装 xgboost 报错ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/fold
安装 xgboost 报错ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/fold
|
Python
Fatal Python error:initsite:Failed to import the site module
Fatal Python error:initsite:Failed to import the site module
501 0
Fatal Python error:initsite:Failed to import the site module