pip install chardet
chardet.detect(bytes) 返回字典:{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}。
import urllib.request
import chardet
url = 'https://www.baidu.com'
response = urllib.request.urlopen(url)
html_bytes = response.read()
result = chardet.detect(html_bytes)
print(f"編碼: {result['encoding']}, 置信度: {result['confidence']}")
def get_charset(url: str) -> str:
"""自動獲取網頁字符集"""
try:
with urllib.request.urlopen(url, timeout=10) as resp:
content = resp.read()
return chardet.detect(content)['encoding']
except Exception as e:
print(f"檢測失敗: {e}")
return 'utf-8' # 默認回退
if __name__ == '__main__':
sites = ['https://www.csdn.net/', 'https://www.imooc.com/', 'https://www.51cto.com/']
for site in sites:
print(f"{site} -> {get_charset(site)}")
detect(bytes_data)。confidence > 0.8 才信任結果,否則回退默認編碼。bytes,直接傳給 detect 即可。