求助:使用BeautifulSoup4爬取维基百科GDP表格的表头与子表头
解决BS4爬取维基百科各国名义GDP列表的表头与子表头问题
问题分析
你当前的代码仅提取了表格的第一行主表头,但维基百科该页面的表格是复合层级表头(主表头+子表头),且部分主表头存在跨列(colspan)属性,直接取单行表头无法生成符合要求的多级DataFrame列结构。
修改后完整代码
import requests from bs4 import BeautifulSoup import pandas as pd # 请求页面并解析 url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 定位目标表格(页面第一个带wikitable类的表格) gdp_table = soup.find_all('table', class_='wikitable')[0] rows = gdp_table.find_all('tr') # ---------------------- 处理层级表头 ---------------------- # 1. 处理主表头(第一行),处理跨列colspan main_headers = [] for th in rows[0].find_all('th'): text = th.get_text(strip=True) colspan = int(th.get('colspan', 1)) # 默认colspan为1 main_headers.extend([text] * colspan) # 2. 处理子表头(第二行) sub_headers = [th.get_text(strip=True) for th in rows[1].find_all('th')] # 3. 创建多级列名MultiIndex multi_columns = pd.MultiIndex.from_tuples(zip(main_headers, sub_headers), names=['Main', 'Sub']) # ---------------------- 处理表格数据 ---------------------- data_rows = [] for row in rows[2:]: # 从第三行开始是数据行 cols = row.find_all(['td', 'th']) # 第一列是国家名,用<th>标签 row_data = [col.get_text(strip=True) for col in cols] if row_data: # 跳过空行 data_rows.append(row_data) # 创建DataFrame df = pd.DataFrame(data_rows, columns=multi_columns) # 查看前几行 print(df.head())
关键说明
- 跨列处理:针对主表头中带有
colspan属性的单元格(比如"GDP (US$ million)"跨3列),通过extend([text] * colspan)将主表头文本重复对应次数,保证和子表头的数量匹配。 - 多级列名:用
pd.MultiIndex.from_tuples将主、子表头配对,生成和参考截图一致的层级列结构。 - 数据行提取:从第三行开始遍历,同时兼容第一列的
<th>标签(国家/地区名),确保数据完整提取。
内容的提问来源于stack exchange,提问作者NIVEA
相关产品推荐
相关产品推荐

