【发布时间】:2022-09-25 16:44:19
【问题描述】:
有一个网站https://www.hockey-reference.com//leagues/NHL_2022.html 我需要使用 id=div_stats 在 div 中获取表
from bs4 import BeautifulSoup
url = \'https://www.hockey-reference.com/leagues/NHL_2022.html\'
r = requests.get(url=url)
soup = BeautifulSoup(r.text, \'html.parser\')
table = soup.find(\'div\', id=\'div_stats\')
print(table)
#None
响应为 200,但 BeautifulSoup 对象中没有这样的 div。如果我使用 selenium 或手动打开页面 - 它会正确加载。
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
url = \'https://www.hockey-reference.com/leagues/NHL_2022.html\'
with webdriver.Chrome() as browser:
browser.get(url)
#sleep(1)
html = browser.page_source
#r = requests.get(url=url, stream=True)
soup = BeautifulSoup(html, \'html.parser\')
table = soup.find_all(\'div\', id=\'div_stats\')
但是,在使用 webdriver 时,它可能会加载页面很长时间(即使我看到整个页面,它仍然在加载 browser.get(url),并且代码无法继续)。 当表格在 HTML 中时,是否有任何解决方案可以帮助避免硒/停止加载? 我试过:requests.get() 中的流和超时,
for season in seasons:
browser.get(url)
wait = WebDriverWait(browser, 5)
wait.until(EC.visibility_of_element_located((By.ID, \'div_stats\')))
html = browser.execute_script(\'return document.documentElement.outerHTML\')
没有任何效果。
标签: python html selenium-webdriver beautifulsoup python-requests