我正在使用 Chrome 浏览器来测试 WebApp。
有时页面会在很长时间后加载。我需要停止下载或限制他们的下载时间。
在 FireFox 中,我了解 PAGE_LOAD_STRATEGY = "eager"
。
chrome 有类似的东西吗?
P.S.:driver.manage().timeouts().pageLoadTimeout()
有效,但此后对 Webdriver 的任何处理都会抛出 TimeOutException
。
我需要在停止启动后获取页面的当前 url。
最佳答案
ChromeDriver 77.0(支持 Chrome 版本 77)现在支持 eager
作为pageLoadStrategy。
<小时/>Resolved issue 1902: Support eager page load strategy [Pri-2]
来自 Webdriver 规范:
For commands that cause a new document to load, the point at which the command returns is determined by the session’s page loading strategy.
何时 Page Loading
花费太多时间,并且您需要停止下载额外的子资源(图像、css、js 等),您可以更改 pageLoadStrategy
通过webdriver
.
截至撰写本文时, pageLoadStrategy
支持以下值:
normal
此策略导致 Selenium 等待整个页面加载(下载并解析 html 内容和子资源)。
eager
此策略导致 Selenium 等待 DOMContentLoaded 事件(仅下载和解析 html 内容)。
none
此策略会导致 Selenium 在完全接收到初始页面内容(下载了 html 内容)后立即返回。
默认情况下,当Selenium
时加载一个页面,它遵循 normal
pageLoadStrategy
。
这是配置 pageLoadStrategy()
的代码块通过 DesiredCapability 类和 ChromeOptions 类的实例,如下所示: :
使用DesiredCapability类:
package demo; //replace by your own package name import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; public class A_Chrome_DCap_Options { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); DesiredCapabilities dcap = new DesiredCapabilities(); dcap.setCapability("pageLoadStrategy", "normal"); ChromeOptions opt = new ChromeOptions(); opt.merge(dcap); WebDriver driver = new ChromeDriver(opt); driver.get("https://www.google.com/"); System.out.println(driver.getTitle()); driver.quit(); } }
使用 ChromeOptions 类:
package demo; //replace by your own package name import org.openqa.selenium.PageLoadStrategy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class A_Chrome_Options_test { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); ChromeOptions opt = new ChromeOptions(); opt.setPageLoadStrategy(PageLoadStrategy.NORMAL); WebDriver driver = new ChromeDriver(opt); driver.get("https://www.google.com/"); System.out.println(driver.getTitle()); driver.quit(); } }
<小时/>Note :
pageLoadStrategy
valuesnormal
,eager
andnone
is a requirement as per WebDriver W3C Editor's Draft butpageLoadStrategy
value aseager
is still a WIP (Work In Progress) within ChromeDriver implementation. You can find a detailed discussion in “Eager” Page Load Strategy workaround for Chromedriver Selenium in Python
引用文献:
关于selenium - Chrome驱动程序的页面加载策略(更新至Selenium v3.12.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43734797/