这是我想解析的网站:[俄语网站][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库默认转义非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-эт. дом
关于python-2.7 - Scrapy::转储到 json 文件时出现编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23436496/