Skip to main content
 首页 » 编程设计

python之Beautiful Soup 获取动态表数据

2024年10月01日898°冷暖

我有以下代码:

url = 'https://www.basketball-reference.com/leagues/NBA_2017_standings.html#all_expanded_standings' 
html = urlopen(url) 
soup = BeautifulSoup(html, 'lxml') 
 
print(len(soup.findAll('table'))) 
print(soup.findAll('table')) 

网页上有6张表,但只返回4张表。我尝试使用“html.parser”或“html5lib”作为解析器,但都不起作用。

知道如何从网页上获取表格“展开的排名”吗?

谢谢!

请您参考如下方法:

requests 无法获取由 JS 加载的数据。所以,你必须使用 selenium。首先通过pip 安装selenium - pip install selenium 并下载chrome driver并将文件放在您的工作目录中。然后尝试下面的代码。

from bs4 import BeautifulSoup 
import time 
from selenium import webdriver 
 
url = "https://www.basketball-reference.com/leagues/NBA_2017_standings.html" 
browser = webdriver.Chrome() 
 
browser.get(url) 
time.sleep(3) 
html = browser.page_source 
soup = BeautifulSoup(html, "lxml") 
 
print(len(soup.find_all("table"))) 
print(soup.find("table", {"id": "expanded_standings"})) 
 
browser.close() 
browser.quit() 

参见 selenium documentation .

如果您使用的是 Linux 并遇到错误 Chromedriver executable needs to be in the PATH 然后尝试按照这些方式 - link-1 , link-2