2017-08-24 89 views
1

我有以下代碼:美麗的湯取動態表數據

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'作爲解析器,但也沒有工作。

任何想法如何從網頁上獲得表格「擴展的排名」?

謝謝!

+0

其餘由JS加載。 –

+0

你是什麼意思?你知道我可以如何訪問它嗎? – user2993519

+0

您可以使用硒來訪問其餘部分。 – SIM

回答

1

requests無法提取由JS加載的數據。所以,你必須使用selenium。首先通過pip - pip install selenium安裝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() 

請參閱seleniumdocumentation

如果你是在Linux並得到錯誤Chromedriver executable needs to be in the PATH然後嘗試以下的方法 - link-1link-2