python爬虫防乱码方案

python爬虫防乱码方案

一、chardet库

自动检测编码:使用 Python 库 chardet 可以自动检测文本的编码,然后使用检测到的编码来解码文本。你可以尝试使用 chardet 库来检测编码,然后解码网页内容。

  • 案例
import requests
import chardet
from bs4 import BeautifulSoup

# 定义目标网页的URL
url = "https://pic.netbian.com/4kmeinv/index.html"

# 发送HTTP GET请求
response = requests.get(url)

# 使用chardet检测编码
encoding = chardet.detect(response.content)['encoding']

# 解码响应内容
response.encoding = encoding

你可能感兴趣的:(python,爬虫,开发语言)