为什么我的字符串被破解?

时间:2015-10-01 07:08:16

标签: python encoding utf-8 ascii

我遇到了问题,现在是:

from lxml.html import parse
from urllib2 import urlopen
import codecs

parsed = parse(urlopen('http://lakgsa.org/?page_id=18'))
doc = parsed.getroot()
links = doc.findall('.//div/a')
print(links[15:20])
lnk=links[3]
lnk.get('href')
print(lnk.get('href'))
print(lnk.text_content())
with codecs.open('hey.json', 'wb', encoding='utf-8') as file:
    file.write(lnk.text_content())

在此之上运行,我的ubuntu终端和'hey.json'显示在此之后。

'[招聘]ë§ì'ì¤ììì'í°2016年ê¸ëììììììììì<<§³êêμμ³³

字体是中断的。我知道这是编码问题。但无论我尝试其他解决方案,都失败了。

1 个答案:

答案 0 :(得分:0)

问题在于你是双重编码 - 来自远程源的内容已经是UTF-8,然后当你正在编写它时,它会被重新编码。

处理此问题的最快方法是从输出文件encoding=utf-8中删除open()

处理此问题的正确方法是根据远程服务器的Charset定义将输入流转换为Unicode。最简单的方法是使用python-request及其response.text字段。

from lxml.html import parse
import requests
import io

url = 'http://lakgsa.org/'
params = {'page_id': '18'}

response = requests.get(url, params)
parsed = parse(response.text)
doc = parsed.getroot()

links = doc.findall('.//div/a')
print(links[15:20])
lnk=links[3]
lnk.get('href')
print(lnk.get('href'))
print(lnk.text_content())

# io should be used instead of codecs
# you don't need the 'b' mode
with io.open('hey.json', 'w', encoding='utf-8') as file:
    file.write(lnk.text_content())

您可能需要考虑BeautifulSoup,它具有非常好的Unicode支持。