【问题标题】:Scrapy Dynamic Item Class CreationScrapy 动态项目类创建
【发布时间】:2015-04-13 23:01:52
【问题描述】:

不确定如何创建动态项目类:http://scrapy.readthedocs.org/en/latest/topics/practices.html#dynamic-creation-of-item-classes

不太确定我会在哪里使用文档中提供的代码。 我会将其粘贴在 pipelines.py、items.py 中并从蜘蛛的解析函数中调用它吗?还是调用scrapy spider的主脚本文件?

【问题讨论】:

    标签: python scrapy


    【解决方案1】:

    我会将代码 sn-p 放在items.py 中,并在spider 中用于我需要的任何动态项目(可能取决于个人喜好),例如:

    from myproject.items import create_item_class
    
    # base on one of the scrapy example...    
    class MySpider(CrawlSpider):
        # ... name, allowed_domains ... 
        def parse_item(self, response):
            self.log('Hi, this is an item page! %s' % response.url)
            # for need to use a dynamic item
            field_list = ['id', 'name', 'description']
            DynamicItem = create_item_class('DynamicItem', field_list)
            item = DynamicItem()
            # then you can use it here...
            item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
            item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
            item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
            return item
    

    您可能有兴趣阅读Dynamic Creation of Item Classes #398 以获得更好的理解。

    【讨论】:

    • 如果我希望它是一个持久的项目类(即在获取超过一页的字段值后将使用相同的 xpaths/field-values),我会将它放在 def __init__(self, **kw) 代替?然后像这样从解析函数调用它: item = self.DynamicItem() ?
    • @GFix,是的,你也可以这样做,但是如果具有相同字段的 DynamicItem 偶尔会被重用,我更愿意在 items.py 中创建一个项目。
    • @GFix,通常我只将这个sn-p用于我在常规之外发现的一些有趣的项目,你可以说是一次性的。
    • @GFix,xpaths 的输出是什么?在 cmets 中很难解释。你最好打开一个新问题。
    猜你喜欢
    • 2013-07-28
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2022-01-21
    • 2016-06-17
    • 2015-10-31
    • 2012-01-13
    • 1970-01-01
    相关资源
    最近更新 更多