Skip to main content
 首页 » 编程设计

python之如何使用 ItemLoaders 将数据添加到类似字典的项目字段中

2024年11月01日10qq号

我正在使用 Scrapy 的 XPathItemLoader,但它只是 api 文档,向 Item 字段添加值,但没有更深入的 :( 我的意思是:

def parse_item(self, response): 
    loader = XPathItemLoader(response=response) 
    loader.add_xpath('name', '//h1') 

会将xpath找到的值添加到Item.name中,但是如何将它们添加到Item.profile['name']中呢?

请您参考如下方法:

XPathItemLoader.add_xpath不支持写入嵌套字段。你应该构建你的 profile手动听写并通过 add_value 写入方法(以防你仍然需要使用装载机)。或者,您可以编写自己的自定义加载器。

这是一个使用 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() 

通过以下方式运行:scrapy runspider <script_name> --output test.json .

蜘蛛收集 Other areas of Wikipedia 的元素从主要维基百科页面并将其写入字典字段 others .

希望对您有所帮助。