You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析维基百科MIUI页面中MIUI浏览器版本历史表格为DataFrame

解决维基百科MIUI页面浏览器版本历史表格解析问题

你遇到的核心问题是:代码里用的表格class列表太冗余,其中mw-made-collapsible是页面加载后JS动态添加的,静态请求返回的HTML里根本不存在这个class,导致find方法匹配不到目标表格。

下面给出两种可靠的解决思路及完整代码:


方法1:用静态稳定的class组合定位表格

直接使用页面静态HTML中存在的class组合,避开JS动态生成的class:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://en.wikipedia.org/wiki/MIUI'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# 仅保留静态存在的class组合,定位目标表格
table = soup.find('table', class_='wikitable sortable mw-collapsible')

if table:
    # 提取表头与行数据
    rows = table.find_all('tr')
    headers = [th.get_text(strip=True) for th in rows[0].find_all('th')]
    data = []
    
    for row in rows[1:]:
        cols = row.find_all('td')
        if cols:
            version = cols[0].get_text(strip=True)
            release_date = cols[1].get_text(strip=True)
            data.append({headers[0]: version, headers[1]: release_date})
    
    # 转为DataFrame
    df = pd.DataFrame(data)
    print(df)
else:
    print("未找到目标表格")

方法2:通过章节标题精准定位表格

先找到"MIUI Browser version history"章节的位置,再取其下方的第一个表格,完全避免class变化的影响:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://en.wikipedia.org/wiki/MIUI'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# 定位章节标题的锚点
section_anchor = soup.find('span', id='MIUI_Browser_version_history')
if section_anchor:
    # 获取标题所在的h3标签,再找其后续的第一个表格
    h3_tag = section_anchor.parent
    table = h3_tag.find_next_sibling('table', class_='wikitable')
    
    if table:
        rows = table.find_all('tr')
        headers = [th.get_text(strip=True) for th in rows[0].find_all('th')]
        data = []
        
        for row in rows[1:]:
            cols = row.find_all('td')
            if cols:
                version = cols[0].get_text(strip=True)
                release_date = cols[1].get_text(strip=True)
                data.append({headers[0]: version, headers[1]: release_date})
        
        df = pd.DataFrame(data)
        print(df)
    else:
        print("目标章节下未找到表格")
else:
    print("未找到目标章节")

内容的提问来源于stack exchange,提问作者John Niroupman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 23:27:18