将<requests.models.Response>转换为对象



>我发送了一个请求并收到了如下所示的响应。python 类型(响应(等于 requests.models.Response

下面的代码会将对象保存到 html 文件中,但我想将其转换为 BeautifulSoup python 对象(var: html_file(,而无需将其保存到本地文件中。我该怎么做?谢谢。

   response = requests.get(...)
   with open(local_filename, 'wb') as f:
     for chunk in response.iter_content(chunk_size=1024):
       if chunk:
         f.write(chunk)
         f.flush()
   html_file = BeautifulSoup(open(html_file_dir), "html.parser")

使用响应.text属性以字符串形式读取数据。示例如何在不写入文件的情况下读取https://www.google.com

import requests
from bs4 import BeautifulSoup
url = 'https://www.google.com'
response = requests.get(url)
html_file = BeautifulSoup(response.text, "html.parser")
print(html_file.prettify())

延伸阅读:

请求的开发人员接口

最新更新