簡體   English   中英

為scrapy CrawlSpider方法創建單元測試

[英]Create unit-test for method of scrapy CrawlSpider

最初的問題

我正在編寫一個CrawlSpider類(使用scrapy庫)並依賴大量scrapy 異步魔法來使其工作。 這是剝離的:

class MySpider(CrawlSpider):
    rules = [Rule(LinkExtractor(allow='myregex'), callback='parse_page')]
    # some other class attributes

    def __init__(self, *args, **kwargs):
        super(MySpider, self).__init__(*args, **kwargs)
        self.response = None
        self.loader = None

    def parse_page_section(self):
        soup = BeautifulSoup(self.response.body, 'lxml')
        # Complicated scraping logic using BeautifulSoup
        self.loader.add_value(mykey, myvalue)

    # more methods parsing other sections of the page
    # also using self.response and self.loader

    def parse_page(self, response):
        self.response = response
        self.loader = ItemLoader(item=Item(), response=response)
        self.parse_page_section()
        # call other methods to collect more stuff
        self.loader.load_item()

類屬性rule告訴我的蜘蛛跟隨某些鏈接並在下載網頁后跳轉到回調函數 我的目標是測試名為parse_page_section的解析方法,而不運行爬蟲或甚至發出真正的HTTP請求。

我嘗試了什么

本能地,我轉向了mock庫。 我理解你如何模擬一個函數來測試它是否被調用(使用哪些參數以及是否存在任何副作用......),但這不是我想要的。 我想實例化一個假對象MySpider並分配足夠的屬性,以便能夠在其上調用parse_page_section方法。

在上面的例子中,我需要一個response對象來實例化我的ItemLoader ,特別是self.response.body屬性來實例化我的BeautifulSoup 原則上,我可以制作這樣的假物品:

from argparse import Namespace

my_spider = MySpider(CrawlSpider)
my_spider.response = NameSpace(body='<html>...</html>')

這適用於BeautifulSoup類,但我需要添加更多屬性來創建ItemLoader對象。 對於更復雜的情況,它會變得丑陋和難以管理。

我的問題

這是正確的方法嗎? 我在網上找不到類似的例子,所以我認為我的方法可能在更基礎的層面上是錯誤的。 任何見解將不勝感激。

你見過蜘蛛合同嗎?

這允許您測試蜘蛛的每個回調,而無需大量代碼。 例如:

def parse(self, response):
    """ This function parses a sample response. Some contracts are mingled
    with this docstring.

    @url http://www.amazon.com/s?field-keywords=selfish+gene
    @returns items 1 16
    @returns requests 0 0
    @scrapes Title Author Year Price
    """

使用check命令運行合同檢查。

看看這個答案 ,如果你想要更大的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM