Python 如何使用ItemLoader将数据添加到类似dict的项字段?
我使用的是Scrapy的XpatientLoader,但它的api仅用于向项字段添加值,而不是更深层次的文档:(我的意思是:Python 如何使用ItemLoader将数据添加到类似dict的项字段?,python,web-scraping,scrapy,Python,Web Scraping,Scrapy,我使用的是Scrapy的XpatientLoader,但它的api仅用于向项字段添加值,而不是更深层次的文档:(我的意思是: 将xpath找到的值添加到Item.name,但是如何将它们添加到Item.profile['name']?XPathItemLoader。add\u xpath不支持写入嵌套字段。您应该手动构建配置文件dict,并通过add\u value方法写入(以防您仍然需要使用加载器)。或者,您可以编写自己的自定义加载器 下面是一个使用添加值的示例: from scrapy.co
将xpath找到的值添加到
Item.name
,但是如何将它们添加到Item.profile['name']
?XPathItemLoader。add\u xpath
不支持写入嵌套字段。您应该手动构建配置文件dict,并通过add\u value
方法写入(以防您仍然需要使用加载器)。或者,您可以编写自己的自定义加载器
下面是一个使用添加值的示例:
from scrapy.contrib.loader import XPathItemLoader
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
class TestItem(Item):
others = Field()
class WikiSpider(BaseSpider):
name = "wiki"
allowed_domains = ["en.wikipedia.org"]
start_urls = ["http://en.wikipedia.org/wiki/Main_Page"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
loader = XPathItemLoader(item=TestItem(), response=response)
others = {}
crawled_items = hxs.select('//div[@id="mp-other"]/ul/li/b/a')
for item in crawled_items:
href = item.select('@href').extract()[0]
name = item.select('text()').extract()[0]
others[name] = href
loader.add_value('others', others)
return loader.load_item()
name = response.xpath('//h1/text()').extract_first()
loader.add_value('profile', {'name':name})
通过:scrapy runspider--output test.json
运行它
蜘蛛从Wikipedia主页面收集Wikipedia的其他区域
项,并将其写入字典字段其他
希望对您有所帮助。这是scrapy.loader.Itemloader的默认设置:
class ItemLoader(object):
default_item_class = Item
default_input_processor = Identity()
default_output_processor = Identity()
default_selector_class = Selector
当您使用add_value
add_xpath
add_css
时,输入和输出处理器是Identify()
,这意味着什么都不做。因此您可以使用add value
:
from scrapy.contrib.loader import XPathItemLoader
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
class TestItem(Item):
others = Field()
class WikiSpider(BaseSpider):
name = "wiki"
allowed_domains = ["en.wikipedia.org"]
start_urls = ["http://en.wikipedia.org/wiki/Main_Page"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
loader = XPathItemLoader(item=TestItem(), response=response)
others = {}
crawled_items = hxs.select('//div[@id="mp-other"]/ul/li/b/a')
for item in crawled_items:
href = item.select('@href').extract()[0]
name = item.select('text()').extract()[0]
others[name] = href
loader.add_value('others', others)
return loader.load_item()
name = response.xpath('//h1/text()').extract_first()
loader.add_value('profile', {'name':name})
答案有助于解决问题吗?有什么需要改进的吗?谢谢。