不确定如何创建动态项目类:http://scrapy.readthedocs.org/en/latest/topics/practices.html#dynamic-creation-of-item-classes
我不太确定在哪里使用文档中提供的代码。 我会把它粘在pipelines.py,items.py中并从蜘蛛的解析函数中调用它吗?或调用scrapy蜘蛛的主脚本文件?
答案 0 :(得分:1)
我会将代码段放在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以便更好地理解。