【问题标题】:How to get byte representation of HTML response like with the Python 'requests' library 'response.content'如何像 Python 'requests' 库 'response.content' 一样获取 HTML 响应的字节表示
【发布时间】:2020-03-20 00:28:34
【问题描述】:

使用 Python 请求库,在获得响应时,response.content 的确切表示是什么,包括 UTF 编码?


如何获取字符串或文本(如 response.text)并将其转换为精确的表示形式,即 response.content

示例:

response = requests.get('https://stackoverflow.com')

response.content 是一个字节表示。

如果我要使用response.text,我将如何在 Python 中将其转换为 response.content


原因:

我有另一个 HTTP 库,它以字符串格式返回 HTML 响应(Selenium:driver.page_source),我需要将它传递给另一个库 lxml,它只接受与请求完全相同的字节表示 response.content形成。

【问题讨论】:

  • 到底是什么问题?你有没有尝试过,做过任何研究?

标签: python selenium python-requests lxml


【解决方案1】:

您可以使用编码(可能是'utf-8')将字符串格式转换为bytes

import requests
response = requests.get('https://stackoverflow.com')
response.content == response.text  # False
response.content == bytes(response.text, encoding='utf-8')  # True

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多