1

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

从这个问题建议您需要构建一个管道,答案未提供超出问题SO scrapy 序列化程序的范围

所以参考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
4

1 回答 1

2

问题在这里:

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

你刚刚忘记打电话了extract。将其替换为:

item['venue'] = site.xpath('.//@venue').extract()
于 2016-01-24T04:55:01.423 回答