如何使用python从Wikipedia表中只提取一列的链接?

如何使用python从Wikipedia表中只提取一列的链接?,python,web-scraping,beautifulsoup,wikipedia,Python,Web Scraping,Beautifulsoup,Wikipedia,我是初学者,这是我在论坛上的第一个问题。 正如标题中所述,我的目标是仅从该wiki页面表的一列中删除链接: 我已经在那个论坛上看过了好几篇文章(特别是这篇),但似乎没有一篇能回答我的问题(据我所知,使用数据框不是一个解决方案,因为它是一种复制/粘贴表格的方式,而我想获得链接) 这是到目前为止我的代码 import requests res=requests.get("https://fr.wikipedia.org/wiki/Liste_des_communes_de_l%27Ain&

我是初学者,这是我在论坛上的第一个问题。 正如标题中所述,我的目标是仅从该wiki页面表的一列中删除链接:

我已经在那个论坛上看过了好几篇文章(特别是这篇),但似乎没有一篇能回答我的问题(据我所知,使用数据框不是一个解决方案,因为它是一种复制/粘贴表格的方式,而我想获得链接)

这是到目前为止我的代码

import requests
res=requests.get("https://fr.wikipedia.org/wiki/Liste_des_communes_de_l%27Ain")

from bs4 import BeautifulSoup as bs
soup=bs(res.text,"html.parser")
table=soup.find('table','wikitable')
links=table.findAll('a')
communes={}
for link in links:
    url=link.get("href","")
    communes[link.text.strip()]=url
print(communes)

提前感谢您的回答

要刮取特定列,可以使用CSS选择器。要使用CSS选择器,请使用方法而不是

例如,要仅刮除第六列,请使用
soup选择第六列
。选择(“td:nth of type(6)”)

下面是一个示例,说明如何仅打印第五列中的所有链接:

import requests
from bs4 import BeautifulSoup


BASE_URL = "https://fr.wikipedia.org"
URL = "https://fr.wikipedia.org/wiki/Liste_des_communes_de_l%27Ain"

soup = BeautifulSoup(requests.get(URL).content, "html.parser")

# The following will find all `a` tags under the fifth `td` of it's type, which is the fifth column
for tag in soup.select("td:nth-of-type(5) a"):
    print(BASE_URL + tag["href"])
输出:

https://fr.wikipedia.org/wiki/Canton_de_Bourg-en-Bresse-1
https://fr.wikipedia.org/wiki/Canton_de_Bourg-en-Bresse-2
https://fr.wikipedia.org/wiki/Canton_d%27Amb%C3%A9rieu-en-Bugey
https://fr.wikipedia.org/wiki/Canton_de_Villars-les-Dombes
https://fr.wikipedia.org/wiki/Canton_de_Belley
...

如果您想要第一列,其中包含commons,您还可以在attribute=value选择器中使用它左对齐的事实

commune_links = ['https://fr.wikipedia.org' + i['href'] for i in soup.select('[style="text-align:left;"] a')]

你特别想搜刮哪一个专栏?只有第一个专栏可以获得城市的链接。非常感谢你的回答非常有用!我点击了一个按钮,说“你的答案很有用”,但这还不算,因为我现在还不到15岁reputation@AnthonySULIO只需点击答案旁边的复选标记。好的,我就这么做了!非常感谢,这非常有用!!你知道为什么它使用这个链接而不是这个链接吗?对于那个链接,你还需要指定表
commune\u links=['https://fr.wikipedia.org“+i['href']表示汤中的i。选择('.titre en couleur[style=“text align:left;”“]a”)
好的,我现在就知道了,谢谢!您需要
汤。选择(“.titre en couleur td[数据排序值]”)