首页 > 解决方案 > 我如何获得第二个表类?

问题描述

我正在尝试使用 BeautifulSoup 在维基百科页面中查找表。我知道如何获取第一个表,但如何获取具有相同类别的第二个表(标准普尔 500 成分股列表的最新更改)wikitable sortable

我的代码:

import bs4 as bs
import requests

url='https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
r=requests.get(url)
url=r.content
soup = bs.BeautifulSoup(url,'html.parser')

tab = soup.find("table",{"class":"wikitable sortable"})

https://en.wikipedia.org/wiki/List_of_S%26P_500_companies

标签: pythonbeautifulsoup

解决方案


您可以使用soup.find_all和访问最后一个表。由于只有两个table标签wikitable sortable作为其类,结果列表中的最后一个元素将是“最近更改”表:

soup.find_all("table", {"class":"wikitable sortable"})[-1]

推荐阅读