我很難從 Wikipedia 中抓取特定的表格。這是我的代碼。
import pandas as pd
import requests
from bs4 import BeautifulSoup
wikiurl = 'https://en.wikipedia.org/wiki/List_of_towns_in_India_by_population'
table_class = "wikitable sortable jquery-tablesorter"
response = requests.get(wikiurl)
print(response.status_code)
soup = BeautifulSoup(response.text, 'html.parser')
cities = soup.find('table', {"class":"wikitable sortable jquery-tablesorter"})
df = pd.read_html(str(cities))
df=pd.DataFrame(df[0])
print(df.to_string())
當您檢查頁面時,該類取自 table 標記內的資訊,我使用 Edge 作為瀏覽器。更改索引 (df[0]) 會導致它說索引超出范圍。
每個表的維基百科源代碼中是否有唯一識別符號?我想要一個解決方案,但我真的很想知道我哪里出錯了,因為我覺得我很接近并且理解這一點。
uj5u.com熱心網友回復:
我認為您的主要困難在于提取與您的班級相對應的 html..."wikitable sortable jquery-tablesorter"實際上是三個獨立的班級,并且需要在字典中成為單獨的條目。我在下面的代碼中包含了其中兩個條目。
希望這會有所幫助:
import pandas as pd
import requests
from bs4 import BeautifulSoup
wikiurl = 'https://en.wikipedia.org/wiki/List_of_towns_in_India_by_population'
table_class = "wikitable sortable jquery-tablesorter"
response = requests.get(wikiurl)
print(response.status_code)
# 200
soup = BeautifulSoup(response.text, 'html.parser')
cities = soup.find_all('table', {"class": "wikitable", "class": "sortable"})
print(cities[0])
# <table >
# <tbody><tr>
# <th>Name of Town
# </th>
# <th>State
# ....
tables = pd.read_html(str(cities[0]))
print(tables[0])
# Name of Town State ... Population (2011) Ref
# 0 Achhnera Uttar Pradesh ... 22781 NaN
# 1 Adalaj Gujarat ... 11957 NaN
# 2 Adoor Kerala ... 29171 NaN
# ....
uj5u.com熱心網友回復:
不要直接決議 HTML。使用 MediaWiki 提供的 API,如下所示:https ://www.mediawiki.org/wiki/API:Get_the_contents_of_a_page
在您的情況下,我使用方法 2:使用帶有以下 URL的 Parse API : https ://en.wikipedia.org/w/api.php?action=parse&page=List_of_towns_in_India_by_population&prop=text&formatversion=2&format=json
相應地處理結果。您可能仍需要使用 BeautifulSoup 來提取 HTML 表格及其內容
uj5u.com熱心網友回復:
對于更簡單的解決方案,您只需要熊貓。無需請求和 BeautifulSoup
import pandas as pd
wikiurl = 'https://en.wikipedia.org/wiki/List_of_towns_in_India_by_population'
tables = pd.read_html(wikiurl)
在這里,表格將回傳資料框串列,您可以從資料框表[0] ..等中選擇
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414817.html
標籤:
下一篇:同一散點圖上的兩個或多個數量
