|
发表于 2023-6-20 15:46:14
|
显示全部楼层
[b]直接用 .text 应该是不行的,如果你要忽略编码错误可以看下面的方法
在 Python 的 requests 库中,有时会遇到解码文本内容时的编码问题。如果你希望忽略这些错误,你可以尝试用以下方法:
- import requests
- response = requests.get('http://example.com')
- # 使用 errors 参数设置为 'ignore' 来忽略解码错误
- text = response.content.decode('utf-8', errors='ignore')
复制代码
这段代码会尝试以 utf-8 编码来解码响应的内容。如果遇到任何错误,它将忽略这些错误,并继续处理文本。但需要注意的是,这可能会导致某些字符丢失或替换为其他字符。
如果你知道具体的文本编码,你也可以替换 'utf-8' 为你所知道的编码。例如,如果你知道文本是以 'gbk' 编码的,你可以这样写:
- text = response.content.decode('gbk', errors='ignore')
复制代码
如果你不确定正确的编码,你可以尝试使用 chardet 库自动检测编码:
- import requests
- import chardet
- response = requests.get('http://example.com')
- encoding = chardet.detect(response.content)['encoding']
- text = response.content.decode(encoding, errors='ignore')
复制代码
这段代码会使用 chardet.detect() 方法来推断响应内容的编码,然后用推断出的编码来解码文本。[/b] |
|