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

标签 python web-scraping scrapy

我正在使用 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 .

希望对您有所帮助。

关于python - 如何使用 ItemLoaders 将数据添加到类似字典的项目字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469787/

相关文章:

python - 无法抓取

python - Scrapy 蜘蛛没有抓取正确的 div

python - 我无法使用 scrapy 上的规则获取数据

python - 如何使用 Beautiful Soup 以正确的顺序提取数据

python - rpy2 在 debian 上安装问题

python - 是否有一个 Python 持久数据存储具有与 dict 相同的功能(或者如何哄骗 "Shelve"来获得它)?

python - 如何只抓取两个预定义的页面,但它们抓取不同的项目?

python - 页面源不显示 selenium/Python 的广告

python - 值错误 : Found arrays with inconsistent numbers of samples [ 6 1786]

python - 我如何使用 scrapy 提取具有某些文本匹配的链接