如何使用beauthulsoup使用表id提取表

2024-05-16 22:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何使用BeautifulSoup从https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html刮表。在

这个特定的页面有多个表,我希望能够根据表id提取一个特定的表

我尝试了以下操作,返回一个空列表:

import requests
from bs4 import BeautifulSoup
url="https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html"
page=requests.get(url)
soup=BeautifulSoup(page.content, 'html.parser')

table=soup.find_all('table', id='sortableTable0')
print(table)

如果我按同一标记中的表类进行搜索,则可以提取所有表,因此我不确定为什么搜索特定的表id不起作用?在


Tags: httpsimportcomidurlhtmlstatstable
1条回答
网友
1楼 · 发布于 2024-05-16 22:28:31

这个表是通过JavaScript动态生成的,所以您需要使用能够处理它的东西。Python中的一个选项是使用Selenium,如下所示:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html")

html = driver.page_source
soup = BeautifulSoup(html, "lxml")

table = soup.find_all('table', {'id':'sortableTable0'})
print(table)

有趣的是,页面源在包含表的div之前有以下元素:

<noscript>This page requires Javascript enabled to function<br><br></noscript>

相关问题 更多 >