
1. 使用`WebDriverWait`和`until`方法
Selenium提供了一个`WebDriverWait`类,它允许等待某个条件成为True,直到超时为止。我们可以使用`until`方法来判断某个元素是否存在,如果存在则表示网页已经加载完毕。
python
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# 等待网页加载完毕
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "some_id")))
2. 监听`load`事件
在JavaScript中,网页加载完毕时会触发`load`事件。我们可以通过在Selenium中注入一段JavaScript脚本来监听这个事件,并在事件处理函数中执行Python代码。
python
# 等待网页加载完毕
driver.execute_script("window.onload = function() {arguments[0].call();};")
driver.switch_to.default_content()
driver.execute_script("arguments[0]();", lambda: print("网页已加载完毕"))
3. 检查网络状态
在某些情况下,网页内容可能已经渲染完毕,但是可能还在加载一些资源(如图片、CSS等)。我们可以通过检查浏览器的网络状态来判断是否所有资源都已经加载完毕。
python
# 等待网页加载完毕
driver.implicitly_wait(10)
while True:
if not driver.get_log("performance"):
break
elif "NetworkError" in driver.get_log("performance"):
break
else:
time.sleep(1)
4. 使用`until_not`方法
如果网页中有一些动态加载的内容,我们可能需要等待
更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv183708