【问题标题】:Scrapy exports invalid jsonScrapy 导出无效的 json
【发布时间】:2013-08-24 06:26:52
【问题描述】:

我的解析是这样的:

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select("//tr/td")
    items = []
    for titles in titles:
        item = MyItem()
        item['title'] = titles.select('h3/a/text()').extract()
        items.append(item)
    return items

为什么会这样输出json:

[{"title": ["random title #1"]},
{"title": ["random title #2"]}]

【问题讨论】:

  • 这是有效的 JSON。你从哪里得到这个输出?发布抓取的所有输出。
  • 我通过 cmdline 执行此操作:scrapy crawl myspider -o items.json -t json - 我猜我不明白 [] 来自哪里。应该是纯文本项。
  • @agf:Scrapy 将列表和生成器解包为单个项目。
  • 好的,我使用了来自stackoverflow.com/a/11870713/1002493 的快速修复及其工作。有什么更好的解决方案?

标签: python json scrapy


【解决方案1】:

titles.select('h3/a/text()').extract() 返回一个列表,所以你得到一个列表。 Scrapy 不会对您的项目结构做出任何假设。

快速解决方法是获得第一个结果:

item['title'] = titles.select('h3/a/text()').extract()[0]

更好的解决方案是使用项目加载器并使用TakeFirst() 作为输出处理器:

from scrapy.contrib.loader import XPathItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose

class YourItemLoader(XPathItemLoader):
    default_item_class = YourItemClass

    default_input_processor = MapCompose(unicode.strip)
    default_output_processor = TakeFirst()

    # title_in = MapCompose(unicode.strip)

并以这种方式加载项目:

def parse(self, response):
    hxs = HtmlXPathSelector(response)

    for title in hxs.select("//tr/td"):
        loader = YourItemLoader(selector=title, response=response)
        loader.add_xpath('title', 'h3/a/text()')

        yield loader.load_item()

【讨论】:

    【解决方案2】:

    作为替代的简单答案,您可以编写一个这样的辅助函数:

    def extractor(xpathselector, selector):
        """
        Helper function that extract info from xpathselector object
        using the selector constrains.
        """
        val = xpathselector.select(selector).extract()
        return val[0] if val else None
    

    然后这样称呼它:

    item['title'] = extractor(titles, 'h3/a/text()')
    

    【讨论】:

      猜你喜欢
      • 2011-12-11
      • 2015-02-27
      • 2018-09-13
      • 2014-02-19
      • 2017-04-04
      • 2016-10-18
      • 2021-01-28
      • 1970-01-01
      • 2020-02-23
      相关资源
      最近更新 更多