【问题标题】:Scrapy:: issue with encoding when dumping to the json fileScrapy:: 转储到 json 文件时出现编码问题
【发布时间】:2014-06-19 15:08:57
【问题描述】:

这里是网站,我想解析:[俄语网站][1]

这是提取我需要的信息的代码:

# -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from flats.items import FlatsItem

class DmozSpider(Spider):
name = "dmoz"
start_urls = ['http://rieltor.ua/flats-sale/?ncrnd=6510']

def parse(self, response):
    sel=Selector(response)
    flats=sel.xpath('//*[@id="content"]')
    flats_stored_info=[]
    flat_item=FlatsItem()
    for flat in flats:
        flat_item['square']=[s.encode("utf-8") for s in sel.xpath('//div/strong[@class="param"][1]/text()').extract()]
        flat_item['rooms_floor_floors']=[s.encode("utf-8") for s in sel.xpath('//div/strong[@class="param"][2]/text()').extract()]
        flat_item['address']=[s.encode("utf-8") for s in flat.xpath('//*[@id="content"]//h2/a/text()').extract()]
        flat_item['price']=[s.encode("utf-8") for s in flat.xpath('//div[@class="cost"]/strong/text()').extract()]
        flat_item['subway']=[s.encode("utf-8") for s in flat.xpath('//span[@class="flag flag-location"]/a/text()').extract()]
        flats_stored_info.append(flat_item)
    return  flats_stored_info

我如何转储到 json 文件

scrapy crawl dmoz -o items.json -t json

问题是当我替换上面的代码以在控制台中打印提取的信息时,例如:

    flat_item['square']=sel.xpath('//div/strong[@class="param"][1]/text()').extract()
    for bla in flat_item['square']:
        print bla

脚本以俄语正确显示信息。

但是,当我使用脚本的第一个版本(编码为 utf-8)转储抓取的信息时,它会写入 json 文件,如下所示:

[{"square": ["2-\u043a\u043e\u043c\u043d., 16 \u044d\u0442\u0430\u0436 16-\u044d\u0442. \u0434\u043e\u043c", "1-\u043a\u043e\u043c\u043d., 

如何将信息转储到俄语的 json 文件中?谢谢你的建议。 [1]:http://rieltor.ua/flats-sale/?ncrnd=6510

【问题讨论】:

  • 你能展示一下你是如何转储到 json 的吗?斯帕西博。
  • 请看编辑后的帖子。

标签: python-2.7 encoding scrapy


【解决方案1】:

编码正确,只是json库默认转义了非ascii字符。

您可以加载数据并使用它(从您的示例中复制数据):

>>> import json
>>> print json.loads('"2-\u043a\u043e\u043c\u043d., 16 \u044d\u0442\u0430\u0436 16-\u044d\u0442. \u0434\u043e\u043c"')
2-комн., 16 этаж 16-эт. дом

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    相关资源
    最近更新 更多