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

使用Beautiful Soup爬取维基银行列表返回空列表问题排查

问题原因及解决办法

1. 表格ID匹配错误

你要找的表格,其ID并不是By_market_capitalization——这个ID属于页面中「按市值排名」的章节标题,而非表格本身。维基百科该页面中,目标表格的实际ID是table-by-market-capitalization。

2. 字典键的语法问题

代码中{id : "By_market_capitalization"}的写法有误:字典的键需要是字符串类型,应该写成{'id': "目标ID"},否则会因为id未定义触发NameError(你这里返回空列表,大概率是实际代码中键的写法正确,但用错了表格ID)。

修正后的代码

import requests
from bs4 import BeautifulSoup as bs

html_data = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks')
html_data_text = html_data.text

soup = bs(html_data_text, 'html.parser')
# 使用正确的表格ID查找
table = soup.find_all('table', {'id': 'table-by-market-capitalization'})
print(table)

如果担心页面ID后续变更,也可以通过章节定位表格:先找到ID为By_market_capitalization的章节,再取其下的第一个表格:

import requests
from bs4 import BeautifulSoup as bs

html_data = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks')
html_data_text = html_data.text

soup = bs(html_data_text, 'html.parser')
# 先定位章节,再取对应表格
section = soup.find('span', {'id': 'By_market_capitalization'}).parent
table = section.find_next('table', class_='wikitable')
print(table)

内容的提问来源于stack exchange,提问作者David Schlosser

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:25