response.text 与 response.content

import requests

response1=requests.get("http://www.sina.com")
print(response1.request.headers)
print(response1.content.decode())

response2=requests.get("http://www.sina.com")
print(response2.request.headers)
print(response2.text)
  • 使用response.text 时,Requests 会基于 HTTP 响应的文本编码自动解码响应内容,大多数 Unicode 字符集都能被无缝地解码。
  • 使用response.content 时,返回的是服务器响应数据的原始二进制字节流,可以用来保存图片等二进制文件。
### 处理 `response.text` 返回 HTML 而不是 JSON 的情况 当使用 Python 的 `requests` 库发送 HTTP 请求时,有时服务器可能返回的是 HTML 文档而非预期的 JSON 数据。为了确认响应内容的实际格式,可以通过检查响应头中的 `Content-Type` 字段来判断。 ```python import requests response = requests.get('https://example.com') content_type = response.headers.get('Content-Type', '') if 'application/json' in content_type.lower(): try: data = response.json() print(data) except ValueError as e: print(f"Failed to parse JSON: {e}") elif 'text/html' in content_type.lower(): html_content = response.text print(html_content[:500]) # 打印前500字符以便查看部分内容 else: print("Unknown Content Type:", content_type) ``` 如果确实接收到的是 HTML 内容,则可以根据具体需求采取不同措施: - **解析 HTML**: 使用 BeautifulSoup 或 lxml 等库解析 HTML 并提取所需信息。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') title = soup.title.string print(title) ``` - **调试 API 请求**: 如果本应接收 JSON 却得到了 HTML,可能是由于 URL 错误、缺少必要的查询参数或者认证信息不正确等原因造成的。此时应该仔细核对请求配置,并查阅官方文档确保一切设置无误。 - **错误处理机制**: 增强程序健壮性,在遇到意外类型的响应时能够妥善应对而不至于崩溃。 通过上述方式可以有效处理 `response.text` 返回 HTML 的情形[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值