我正在学习Python和BeautifulSoup
我正在尝试做一些网络抓取:
让我先描述一下我想要做什么?
维基页面:https://en.m.wikipedia.org/wiki/List_of_largest_banks
我正在尝试打印
<span class="mw-headline" id="By_market_capitalization" tabindex="0" role="button" aria-controls="content-collapsible-block-1" aria-expanded="true">By market capitalization</span>
我想打印出文本:By market capitalization
然后是银行表格的文本:例子:按市值计
帽率466.1 300
接近你的目标-找到标题和下一个table
,并通过pandas.read_html()
将其转换为数据框架。
header = soup.select_one('h2:has(>#By_market_capitalization)')
pd.read_html(str(header.find_next('table')))[0]
或
header = soup.select_one('h2:has(>#By_market_capitalization)')
pd.read_html(html_text, match='Market cap')[0]
from bs4 import BeautifulSoup
import requests
import panda as pd
html_text = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks').text
soup = BeautifulSoup(html_text, 'lxml')
header = soup.select_one('h2:has(>#By_market_capitalization)')
print(header.span.text)
print(pd.read_html(str(header.find_next('table')))[0].to_markdown(index=False))
from bs4 import BeautifulSoup
import requests
import panda as pd
html_text = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks').text
soup = BeautifulSoup(html_text, 'lxml')
header = soup.select_one('h2:has(>#By_market_capitalization)')
print(header.span.text)
print(pd.read_html(str(header.find_next('table')))[0].to_markdown(index=False))
输出按市值计
市值(十亿美元)466.21 [5] 中国工商银行295.65 美国银行214.34中国建设银行 中国农业银行 汇丰控股有限公司169.47 花旗集团(Citigroup Inc .)163.58中国银行 招商银行 加拿大皇家银行 多伦多道明银行
您知道所需的标题,您可以直接打印。然后,对于pandas,您可以使用目标表中的唯一搜索词作为更直接的选择方法:
import pandas as pd
df = pd.read_html('https://en.m.wikipedia.org/wiki/List_of_largest_banks', match = 'Market cap')[0].reset_index(level = 0, drop = True)
print('By market capitalization')
print()
print(df.to_markdown(index = False))