我學習 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
然后是銀行表的文本:示例:按市值
| 秩 | 銀行 | 上限率 |
|---|---|---|
| 1 | 摩根大通 | 466.1 |
| 2 | 中國銀行 | 300 |
一直到50
我的代碼開始是這樣的:
from bs4 import
import requests
html_text = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks').text
soup = BeautifulSoup(html_text, 'lxml')
# text = soup.find('span', class_='mw-headline', id='By_market_capitalization').text
Ak_soup = soup.find_all('section', class_='mf-section-2 collapsible-block open-block', id='content-collapsible-block-1')
print(Ak_soup)
我相信我的問題更多是在 html 方面:但我完全迷失了:我檢查了我認為要查找的元素和標簽
{section class_='mf-section-2 collapsible-block open-block'}
uj5u.com熱心網友回復:
接近您的目標 - 找到標題,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))
輸出
按市值
| 秩 | 銀行名稱 | 市值(十億美元) |
|---|---|---|
| 1 | 摩根大通 | 466.21[5] |
| 2 | 中國工商銀行 | 295.65 |
| 3 | 美國銀行 | 279.73 |
| 4 | 富國銀行 | 214.34 |
| 5 | 中國建設銀行 | 207.98 |
| 6 | 中國農業銀行 | 181.49 |
| 7 | 匯豐控股有限公司 | 169.47 |
| 8 | 花旗集團 | 163.58 |
| 9 | 中國銀行 | 151.15 |
| 10 | 招商銀行 | 133.37 |
| 11 | 加拿大皇家銀行 | 113.80 |
| 12 | 多倫多道明銀行 | 106.61 |
...
uj5u.com熱心網友回復:
如您所知,您可以直接列印所需的標題。然后使用 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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485043.html
上一篇:從瀏覽器復制的CSS選擇器在Python中使用BeautifulSoup4回傳不同的結果
下一篇:如何將串列中的物件分配給變數?
