Python爬虫出现乱码通常由以下原因导致:
import chardet
import requests
resp = requests.get('http://example.com')
encoding = chardet.detect(resp.content)['encoding']
text = resp.content.decode(encoding)
对于中文网页常见编码:
# UTF-8解码
text = resp.content.decode('utf-8')
# GBK/GB2312解码
text = resp.content.decode('gbk')
# 带错误处理的解码
text = resp.content.decode('gb18030', errors='ignore')
from bs4 import BeautifulSoup
soup = BeautifulSoup(resp.content, 'html.parser',
from_encoding='gb18030')
print(soup.prettify())
# 查看服务器返回的编码
print(resp.encoding)
# 手动设置响应编码
resp.encoding = 'gbk'
对于特殊编码情况: