对字符串python的Httpresponse

acb*_*824 3 python string httpresponse python-3.5

我正在尝试显示一个网页,但由于它不会将对象视为字符串,因此无法正确显示换行符(显示\n)。我怎样才能正确地使结果成为一个字符串,因为这似乎不起作用。谢谢!

result = urllib.request.urlopen(requesturl).read()
return str(result)
Run Code Online (Sandbox Code Playgroud)

Ben*_*ell 5

正如在解释这个职位,你需要处理你的内容类型有响应的字符编码。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
Run Code Online (Sandbox Code Playgroud)