2015-10-01 29 views
-2

而且我陷进问题,那就是:为什么我的字符串被破解?

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ëê¸ë¡ë²I Iê³μì±ëª¨ì§ê³μê³'

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

+1

*您如何阅读和打印文件内容?您的代码正确地生成UTF-8输出,但您正在读取该错误编码生成的[Mojibake](https://en.wikipedia.org/wiki/Mojibake)的UTF-8输出。 –

+0

我可以通过以CP1256打开UTF-8文件来重现输出。你的Python代码是*很好*,这是你以后对文件所做的事情。 –

+0

最好以你想要完成的目标开始发帖。 “而我陷入问题,这里是”不是一个理想的开始问题的方式。我们不知道后面的代码应该做什么。努力吸引我们。 – dbliss

回答

0

问题是你是双重编码 - 来自远程源的内容已经是UTF-8,那么当你写它时,它又被编码了。

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

解决此问题的正确方法是将输入流转换为基于远程服务器的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支持。

相关问题