【问题标题】:How to test my scrapy method with unitest class如何使用单元测试类测试我的scrapy方法
【发布时间】:2015-11-02 13:31:45
【问题描述】:

我想在我的蜘蛛中尝试一些方法。 例如在我的项目中,我有这个架构:

 toto/
├── __init__.py
├── items.py
├── pipelines.py
├── settings.py
├── spiders
│   ├── __init__.py
│   └── mySpider.py
└── Unitest
    └── unitest.py

我的unitest.py 看起来像这样:

# -*- coding: utf-8 -*-                                                           
import re
import weakref
import six
import unittest
from scrapy.selector import Selector
from scrapy.crawler import Crawler
from scrapy.utils.project import get_project_settings
from unittest.case import TestCase
from toto.spiders import runSpider

class SelectorTestCase(unittest.TestCase):

    sscls = Selector

    def test_demo(self):
    print "test"

if __name__ == '__main__':
    unittest.main()

还有我的mySpider.py,看起来像这样:

import scrapy

class runSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://blog.scrapinghub.com']

    def parse(self, response):
        for url in response.css('ul li a::attr("href")').re(r'.*/\d\d\d\d/\d\d/$'):
            yield scrapy.Request(response.urljoin(url), self.parse_titles)

    def parse_titles(self, response):
        for post_title in response.css('div.entries > ul > li a::text').extract():
            yield {'title': post_title}

在我的 unitest.py 文件中,如何调用我的蜘蛛? 我试图在我的 unitest.py 文件中添加from toto.spiders import runSpider,但它没有...... 我遇到了这个错误:

Traceback(最近一次调用最后一次):文件“unitest.py”,第 10 行,在 from toto.spiders import runSpider ImportError: No module named toto.spiders

我该如何解决?

【问题讨论】:

  • "但是 [原文如此] 它没有..." - 什么?请更具体地了解正在发生的事情。请注意,测试目录通常是 outside 包的顶层 - 参见例如jeffknupp.com/blog/2013/08/16/…
  • runSpider 在哪里?
  • 你有没有为当前的解释器安装 totoimport toto 可以在任何地方工作吗?
  • 尝试:从 toto.spiders.mySpider 导入运行Spider
  • 我的蜘蛛可以在任何地方工作

标签: python python-2.7 scrapy scrapy-spider


【解决方案1】:

试试:

import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..')) #2 folder back from current file

from spiders.mySpider import runSpider

【讨论】:

  • 在运行时攻击sys.path 表明你做错了什么。
  • 那么有什么选择呢?
  • 实际上安装包,如果它在实践中仍然是一个工作,那么你可以在开发模式下测试它,因为它会出现在CI /客户端安装上,而不依赖于相对目录位置。
  • 不,我会写一个setup.py 然后python setup.py develop 在开发模式下安装包(最好是virtualenv)。
猜你喜欢
  • 2011-09-21
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多