我这样做的方法是创建虚假响应,这样您就可以离线测试解析函数。但是您可以通过使用真实的HTML获得真实的情况。
这种方法的问题是您的本地HTML文件可能无法反映在线的最新状态。因此,如果HTML在线更改,您可能会遇到一个大错误,但是您的测试用例仍会通过。因此,这可能不是测试此方法的最佳方法。
我当前的工作流程是,每当出现错误时,我都会使用url向管理员发送电子邮件。然后针对该特定错误,创建一个HTML文件,其中包含引起错误的内容。然后,我为此创建一个单元测试。
这是我用来创建示例Scrapy http响应以从本地html文件进行测试的代码:
# scrapyproject/tests/responses/__init__.pyimport osfrom scrapy.http import Response, Requestdef fake_response_from_file(file_name, url=None): """ Create a Scrapy fake HTTP response from a HTML file @param file_name: The relative filename from the responses directory,but absolute paths are also accepted. @param url: The URL of the response. returns: A scrapy HTTP response which can be used for unittesting. """ if not url: url = 'http://www.example.com' request = Request(url=url) if not file_name[0] == '/': responses_dir = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(responses_dir, file_name) else: file_path = file_name file_content = open(file_path, 'r').read() response = Response(url=url, request=request, body=file_content) response.encoding = 'utf-8' return response
样本html文件位于scrapyproject / tests / responses / osdir / sample.html中
然后,测试用例可能如下所示:测试用例的位置为scrapyproject / tests / test_osdir.py
import unittestfrom scrapyproject.spiders import osdir_spiderfrom responses import fake_response_from_fileclass OsdirSpiderTest(unittest.TestCase): def setUp(self): self.spider = osdir_spider.DirectorySpider() def _test_item_results(self, results, expected_length): count = 0 permalinks = set() for item in results: self.assertIsNotNone(item['content']) self.assertIsNotNone(item['title']) self.assertEqual(count, expected_length) def test_parse(self): results = self.spider.parse(fake_response_from_file('osdir/sample.html')) self._test_item_results(results, 10)基本上,这就是我测试解析方法的方式,但不仅限于解析方法。如果它变得更复杂,我建议看看Mox



