Requests报”requests.exceptions.ContentDecodingError: Failed to decode response content: {error message} “的原因以及解决办法

yizhihongxing

原因

出现该错误的原因可能是服务器返回了无法解码的响应内容。这通常是由于服务器与客户端使用的编码不同或服务器响应中包含了不可解码的字符所导致的。此外,还可能是因为客户端未正确指定编码格式。

解决办法

在解决此错误之前,需要先确保以下几点:

  • 确认服务器使用的编码格式,如UTF-8、GBK等。

  • 确认客户端请求时指定了正确的编码格式,如headers设置"Content-Type": "text/html;charset=UTF-8"。

接下来,可以尝试以下几种方法:

  • 使用response.content.decode('utf-8')解码响应内容。代码示例:
import requests

response = requests.get('https://example.com')
content = response.content.decode('utf-8')
print(content)
  • 修改请求头中的User-Agent,有些服务端不能识别Python默认请求头。
import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36",
    "Content-Type":"text/html;charset=GBK"
}
response = requests.get('https://example.com', headers=headers)
content = response.content.decode('gbk')
print(content)
  • 尝试使用requests_html库解析响应内容。该库可以自动解决一些编码问题。代码示例:
from requests_html import HTMLSession

session = HTMLSession()
response = session.get('https://example.com')
content = response.html.html
print(content)
  • 如果仍然无法解决问题,可以考虑使用其他方法重新请求或联系服务端开发人员进行修复。

希望以上方法能帮助你解决ContentDecodingError错误。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Requests报”requests.exceptions.ContentDecodingError: Failed to decode response content: {error message} “的原因以及解决办法 - Python技术站

(0)
上一篇 2023年3月19日
下一篇 2023年3月19日

相关文章

合作推广
合作推广
分享本页
返回顶部