【发布时间】: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的主脚本文件?
【问题讨论】:
不确定如何创建动态项目类:http://scrapy.readthedocs.org/en/latest/topics/practices.html#dynamic-creation-of-item-classes
不太确定我会在哪里使用文档中提供的代码。 我会将其粘贴在 pipelines.py、items.py 中并从蜘蛛的解析函数中调用它吗?还是调用scrapy spider的主脚本文件?
【问题讨论】:
我会将代码 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 以获得更好的理解。
【讨论】:
items.py 中创建一个项目。