【问题标题】:Pipeline for item not JSON serializable项目的管道不可 JSON 序列化
【发布时间】:2016-04-30 13:38:05
【问题描述】:

我正在尝试将抓取的 xml 的输出写入 json。由于项目不可序列化,抓取失败。

从this question建议您需要构建管道,未提供答案超出问题SO scrapy serializer

所以指的是scrapy docs 它说明了一个示例,但是文档建议不要使用它

JsonWriterPipeline 的目的只是介绍如何编写 项目管道。如果您真的想将所有刮掉的物品存储到一个 JSON 文件,您应该使用 Feed 导出。

如果我去饲料出口,这会显示

JSON

FEED_FORMAT: json Exporter used: JsonItemExporter 如果出现此警告,请参阅此警告 您正在将 JSON 用于大型提要。

我的问题仍然存在,因为我理解的是从命令行执行。

scrapy runspider myxml.py -o ~/items.json -t json

但是,这会产生我打算使用管道来解决的错误。

TypeError: <bound method SelectorList.extract of [<Selector xpath='.//@venue' data=u'Royal Randwick'>]> is not JSON serializable

如何创建 json 管道来纠正 json 序列化错误?

这是我的代码。

# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
from scrapy.selector import XmlXPathSelector
from conv_xml.items import ConvXmlItem
# https://stackoverflow.com/a/27391649/461887
import json


class MyxmlSpider(scrapy.Spider):
    name = "myxml"

    start_urls = (
        ["file:///home/sayth/Downloads/20160123RAND0.xml"]
    )

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//meeting')
        items = []

        for site in sites:
            item = ConvXmlItem()
            item['venue'] = site.xpath('.//@venue').extract
            item['name'] = site.xpath('.//race/@id').extract()
            item['url'] = site.xpath('.//race/@number').extract()
            item['description'] = site.xpath('.//race/@distance').extract()
            items.append(item)

        return items


        # class JsonWriterPipeline(object):
        #
        #     def __init__(self):
        #         self.file = open('items.jl', 'wb')
        #
        #     def process_item(self, item, spider):
        #         line = json.dumps(dict(item)) + "\n"
        #         self.file.write(line)
        #         return item

【问题讨论】:

    标签: python json serialization scrapy scrapy-pipeline


    【解决方案1】:

    问题出在这里:

    item['venue'] = site.xpath('.//@venue').extract
    

    您刚刚忘记致电extract。替换为:

    item['venue'] = site.xpath('.//@venue').extract()
    

    【讨论】:

    • 哈哈,我讨厌你在一个毫无意义的兔子洞里大肆追逐,谢谢
    • 我掉进了那个该死的兔子洞,谢谢 - 解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 2015-04-10
    • 2013-04-26
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多