Python自动检测requests所获得html文档的编码

使用chardet库自动检测requests所获得html文档的编码

使用requestsBeautifulSoup库获取某个页面带来的乱码问题

使用requests配合BeautifulSoup库,可以轻松地从网页中提取数据。但是,当网页返回的编码格式与Python默认的编码格式不一致时,就会导致乱码问题。

以如下代码为例,它会获取到一段乱码的html:

import requests
from bs4 import BeautifulSoup

# 目标 URL
url = 'https://finance.sina.com.cn/realstock/company/sh600050/nc.shtml'

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

# 检查请求是否成功
if response.status_code == 200:

    # 获取网页内容
    html_content = response.text
    
    # 使用 BeautifulSoup 解析 HTML 内容
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 要查找的 ID
    target_id = 'hqDetails'
    
    # 查找具有特定 ID 的标签
    element = soup.find(id=target_id)
    
    if element:
        # 获取该标签下的 HTML 内容
        element_html = str(element)
        print(f"ID 为 {target_id} 的 HTML 内容:\n{element_html}\n")
        
        # 查找该标签下的所有 table 元素
        tables = element.find_all('table')
        
        if tables:
            for i, table in enumerate(tables):
                print(f"第 {i+1} 个 table 的 HTML 内容:\n{table}\n")
        else:
            print(f"ID 为 {target_id} 的标签下没有 table 元素")
    else:
        print(f"未找到 ID 为 {target_id} 的标签")
else:
    print(f"请求失败,状态码: {response.status_code}")

非英语字符乱码
我们可以通过通过手工指定代码的方式来解决这个问题,例如在response.status_code == 200后,通过response.encoding = 'utf-8'指定代码,又或通过soup = BeautifulSoup(html_content, 'html.parser', from_encoding='utf-8') 来指定编码。

然而,当我们获取的html页面编码不确定的时候,有没有更好的办法让编码监测自动执行呢?这时候chardet编码监测库是一个很好的帮手。

使用 chardet 库自动检测编码

chardet 是一个用于自动检测字符编码的库,可以更准确地检测响应的编码。

安装chardet

pip install chardet

代码应用示例

import requests
from bs4 import BeautifulSoup
import chardet

# 目标 URL
url = 'https://finance.sina.com.cn/realstock/company/sh600050/nc.shtml'

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

# 检查请求是否成功
if response.status_code == 200:
    # 自动检测字符编码
    detected_encoding = chardet.detect(response.content)['encoding']
    
    # 设置响应的编码
    response.encoding = detected_encoding

    # 获取网页内容
    html_content = response.text
    
    # 使用 BeautifulSoup 解析 HTML 内容
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 要查找的 ID
    target_id = 'hqDetails'
    
    # 查找具有特定 ID 的标签
    element = soup.find(id=target_id)
    
    if element:
        # 获取该标签下的 HTML 内容
        element_html = str(element)
        print(f"ID 为 {target_id} 的 HTML 内容:\n{element_html}\n")
        
        # 查找该标签下的所有 table 元素
        tables = element.find_all('table')
        
        if tables:
            for i, table in enumerate(tables):
                print(f"第 {i+1} 个 table 的 HTML 内容:\n{table}\n")
        else:
            print(f"ID 为 {target_id} 的标签下没有 table 元素")
    else:
        print(f"未找到 ID 为 {target_id} 的标签")
else:
    print(f"请求失败,状态码: {response.status_code}")

解决了中文乱码问题
可见,通过使用chardet库,可以有效实现代码的自动检测。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Humbunklung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值