嘗試使用 HDI 決議表并將資料加載到 Pandas DataFrame 中,列:Country、HDI_score。
我堅持使用以下代碼加載 Nation 列:
import requests
import pandas as pd
from bs4 import BeautifulSoup
html = requests.get("https://en.wikipedia.org/wiki/List_of_countries_by_Human_Development_Index")
bsObj = BeautifulSoup(html.text, 'html.parser')
df = pd.DataFrame(columns=['Countries', 'HDI_score'])
for row in table.find_all('tr'):
columns = row.find_all('td')
if(columns != []):
countries = columns[1].text.strip()
hdi_score = columns[2].text.strip()
df = df.append({'Countries': countries, 'HDI_score': hdi_score}, ignore_index=True)
我的代碼的結果
因此,我沒有使用國家/地區名稱,而是從“5 年的排名變化”列中獲取值。我試過更改列的索引,但沒有幫助。
uj5u.com熱心網友回復:
您可以使用 Pandas 來獲取適當的表,match='Rank'為您提供正確的表,然后提取感興趣的列。
import pandas as pd
table = pd.read_html('https://en.wikipedia.org/wiki/List_of_countries_by_Human_Development_Index', match='Rank')[0]
columns = ['Nation','HDI']
table = table.loc[:, columns].iloc[:, :2]
table.columns = columns
print(table)
根據評論,如果您仍在使用 Pandas,我認為 bs4 沒什么意義。見下圖:
import pandas as pd
from bs4 import BeautifulSoup as bs
r = requests.get('https://en.wikipedia.org/wiki/List_of_countries_by_Human_Development_Index')
soup = bs(r.content, 'lxml')
table = pd.read_html(str(soup.select_one('table:has(th:contains("Rank"))')))[0]
columns = ['Nation','HDI']
table = table.loc[:, columns].iloc[:, :2]
table.columns = columns
print(table)
uj5u.com熱心網友回復:
注意 投票給 QHarr 因為它也是pandas我認為最直接的解決方案
此外并回答您的問題 -也可以僅通過BeautifulSoup選擇列。只需結合css selectors和stripped_strings。
例子
import requests
import pandas as pd
from bs4 import BeautifulSoup
html = requests.get("https://en.wikipedia.org/wiki/List_of_countries_by_Human_Development_Index")
bsObj = BeautifulSoup(html.text, 'html.parser')
pd.DataFrame(
[list(r.stripped_strings)[-3:-1] for r in bsObj.select('table tr:has(span[data-sort-value])')],
columns=['Countries', 'HDI_score']
)
輸出
| 國家 | HDI_score |
|---|---|
| 挪威 | 0.957 |
| 愛爾蘭 | 0.955 |
| 瑞士 | 0.955 |
| ... | ... |
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382735.html
上一篇:使用Selenium獲取元素串列
