2017-02-13 48 views
-2

我试图显示一个网页,但由于它没有将对象看作一个字符串,所以没有正确显示换行符(它显示\n)。我怎样才能正确地产生一个字符串,因为这似乎没有工作。谢谢!对字符串python的响应

result = urllib.request.urlopen(requesturl).read() 
return str(result) 
+0

问题不明确。它包含'\ n'的事实并不是一个无效的字符串。这完全是针对'pyqt'吗?或者你只是想打印一个由新行破解的单个字符串? – roganjosh

+0

我想要\ n字符实际上打印一个新行,但由于该类型似乎是httpresponse,因此它将打印字符\ n而不是新行。 – acb10824

回答

2

this post中所述,您需要处理Content-Type中的响应的字符编码。 urllib使用get_content_charset方法提供了一种方便的方法来从头文件中获取此信息。

from urllib.request import urlopen 

with urlopen(request_url) as response: 
    html_response = response.read() 
    encoding = response.headers.get_content_charset('utf-8') 
    decoded_html = html_response.decode(encoding) 
    return decoded_html