如何像使用 Python 'requests' 库'response.content'一样获取 HTML 响应的字节表示形式



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


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

示例:

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

CCD_ 5是字节表示。

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


原因:

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

您可以使用编码(可能是'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

最新更新