簡體   English   中英

如何使用 Selenium WebDriver (Chrome) 打開頁面,而無需等待它在 Python 中加載?

[英]How to open a page with Selenium WebDriver (Chrome), without waiting for it to load in Python?

driver.get(URL)函數在返回執行之前等待頁面完成加載。

在 Java 中有一個方法driver.navigate().to(URL) ,它不會等待頁面加載,但是,我在 Python 中找不到這樣的方法。

對於 firefox,我可以運行profile.set_preference("webdriver.load.strategy", "unstable") ,但是 Chrome 沒有這樣的偏好。

還有driver.set_page_load_timeout(0.2)TimeoutException處理 但是,當處理異常時,chrome 驅動程序停止加載頁面。

編輯:稍微改寫這個問題並添加了一個不起作用的解決方案。

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "none"   # Do not wait for full page load
driver = webdriver.Chrome(desired_capabilities=caps, executable_path="path/to/chromedriver.exe")
driver.get('some url')
#some code to run straight away

此代碼不會等待頁面完全加載,然后才移動到下一行。 使用“無”頁面加載策略時,您可能必須自定義等待以檢查您需要的元素或元素是否已完成加載。

你可以使用:

import time
time.sleep()

或者,如果您只想在元素加載之前等待所需的時間:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

WebDriverWait(driver, timeout=10).until(
    ec.visibility_of_element_located((By.ID, "your_element_id"))
)

這應該可以幫助您完成您正在嘗試做的任何事情。 由於您沒有提供代碼,我只能假設這會起作用,因為我無法為特定網頁提供具體答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM