【问题标题】:Httpresponse to string pythonHttpresponse字符串python
【发布时间】:2017-07-01 22:54:48
【问题描述】:

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

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

【问题讨论】:

  • 问题不清楚。它包含\n 的事实并不会使其成为无效字符串。这完全是针对pyqt 还是您只是想打印一个由新行分隔的字符串?
  • 我希望 \n 字符实际打印一个新行,但是由于类型似乎是 httpresponse,它打印字符 \n 而不是一个新行。

标签: python string httpresponse python-3.5


【解决方案1】:

正如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

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多