Python爬虫解码的问题?

如何用gbk和utf-8自动识别解码???请大神指点,最好能附上原码!!感谢了🙏

在获得响应后,使用response.encoding=response.apparent_encoding识别网页编码即可,示例:

from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests
#parser = 'html.parser'  or 'lxml' (preferred) or 'html5lib'
resp = requests.get("https://www.baidu.com")
resp.encoding=resp.apparent_encoding#去掉这行会出现乱码
print(resp.text)


import requests
r = requests.get('')

if 'xx' in str(r.content, encoding='utf-8'):
    v = str(r.content, encoding='utf-8')
else:
    v = str(r.content, encoding='gbk')

获取内容的字节格式,转字符串设置编码,然后判断某个内容是否存在去确定转换是否成功