UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 112: invalid start byte 错误解决

资源分享 · 2023-07-30

如果在解码过程中出现了UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 112: invalid start byte错误,那可能是因为响应内容并不是有效的UTF-8编码。

你可以尝试使用其他编码来解码响应内容,直到找到正确的编码,例如UTF-8-sig、GBK、ISO-8859-1等。以下是修改后的代码示例:

import requests
from bs4 import BeautifulSoup

url = f'https://jhq8.cn/daan/2023/03/1750323.html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 10; Redmi K30 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Mobile Safari/537.36',
    'Cookie':'__yjs_duid=1_f2e16347b4713b66ac81eff6c331c0a21690716476044; ASPSESSIONIDSCCTRSSA=MGKINBCDMMMGNIIPFMOFLKJG; Hm_lvt_28b554d945bf3b94a6f5b87c453c73ce=1690716477; Hm_lpvt_28b554d945bf3b94a6f5b87c453c73ce=1690717044'
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
    print('请求失败')
    exit()
else:
    encoding = response.apparent_encoding  # 获取响应内容的编码
    soup = BeautifulSoup(response.content.decode(encoding, 'ignore'), 'html.parser')
    data = soup.select('body > div.container.xs-top-15 > div > div > div:nth-child(3) > div > div > div:nth-child(1)')
    print(data[0].text.strip())

在上述代码中,我通过使用response.apparent_encoding获取响应内容的编码,并将其传递给response.content.decode()方法来解码内容。

如果仍然无法解决问题,那可能是因为响应内容并不是标准的HTML文档,或者存在其他复杂的编码问题。你可以尝试打印输出response.content,观察响应内容的具体情况,并根据需要进行进一步的处理。

Theme Jasmine by Kent Liao
辽ICP备2021009421号-2