垃圾动态项目类创建

2024-09-27 21:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

不太确定在哪里使用文档中提供的代码。 我能把这个插进去吗管道.py, 项目.py从蜘蛛的解析函数调用这个函数?或者调用scrapy spider的主脚本文件?在


Tags: ofpyorghttphtmlreadthedocs动态dynamic
1条回答
网友
1楼 · 发布于 2024-09-27 21:27:18

我会将代码段放在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。在

相关问题 更多 >

    热门问题