如何使用 Python 从维基百科中抓取特定的 table?

How do I scrape a particular table from Wikipedia, using Python?

我很难从维基百科中抓取特定的 table。这是我的代码。

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())

class 取自检查页面时 table 标签内的信息,我使用 Edge 作为浏览器。更改索引 (df[0]) 会导致它说索引超出范围。

每个 table 的维基百科源代码中是否有唯一标识符?我想要一个解决方案,但我真的很想知道我哪里出错了,因为我觉得我很接近并理解这一点。

我认为你的主要困难在于提取对应于你的 class 的 html... "wikitable sortable jquery-tablesorter" 实际上是三个独立的 classes 并且需要字典中的单独条目。我在下面的代码中包含了其中两个条目。

希望这对您有所帮助:

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 class="wikitable sortable">
# <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
# ....

不要直接解析 HTML。使用 MediaWiki 提供的 API,如下所示:https://www.mediawiki.org/wiki/API:Get_the_contents_of_a_page

在您的情况下,我使用 方法 2:使用具有以下 URL 的解析 APIhttps://en.wikipedia.org/w/api.php?action=parse&page=List_of_towns_in_India_by_population&prop=text&formatversion=2&format=json

相应地处理结果。您可能仍需要使用 BeautifulSoup 来提取 HTML table 及其内容

为了更简单的解决方案,您只需要 pandas。不需要请求和 BeautifulSoup

import pandas as pd
wikiurl = 'https://en.wikipedia.org/wiki/List_of_towns_in_India_by_population'
tables = pd.read_html(wikiurl)

在这里,表格将 return 列出数据框,您可以 select 从数据框表格 [0] .. 等