如果加载过程花费太长时间,我希望 selenium 强制浏览器重新加载正在加载的页面。
从 StackOverflow 我得到了这段代码
new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd)
.executeScript("return document.readyState").equals("complete"));
将等到页面完全加载,但如果需要超过 30 秒,我希望重新加载。
我怎样才能实现这一目标?
最佳答案
要重新加载网页,以防加载过程花费太长时间,您可以配置 pageLoadTimeout 。 pageLoadTimeout
设置在抛出错误之前等待页面加载完成的时间。如果超时为负数,则页面加载可能无限期。
示例(使用 Selenium v3.141.59 和 GeckoDriver v0.24.0):
代码块:
public class pageLoadTimeout { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe"); WebDriver driver=new FirefoxDriver(); driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS); try{ driver.get("https://www.booking.com/hotel/in/the-taj-mahal-palace-tower.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaGyIAQGYATG4AQbIAQzYAQHoAQH4AQKSAgF5qAID;sid=338ad58d8e83c71e6aa78c67a2996616;dest_id=-2092174;dest_type=city;dist=0;group_adults=2;hip_dst=1;hpos=1;room1=A%2CA;sb_price_type=total;srfid=ccd41231d2f37b82d695970f081412152a59586aX1;srpvid=c71751e539ea01ce;type=total;ucfs=1&#hotelTmpl"); // do your other work here }catch(WebDriverException e){ System.out.println("WebDriverException occured"); } driver.quit(); } }
控制台输出:
1565680787633 mozrunner::runner INFO Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "-marionette" "-foreground" "-no-remote" "-profile" "C:\\Users\\Debanjan.B\\AppData\\Local\\Temp\\rust_mozprofile.3jw3aiyfNAiQ" 1565680826515 Marionette INFO Listening on port 56499 1565680827329 Marionette WARN TLS certificate errors will be ignored for this session Aug 13, 2019 12:50:28 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: W3C Aug 13, 2019 12:50:31 PM org.openqa.selenium.remote.ErrorCodes toStatus WebDriverException occured
您可以在pageLoadTimeout in Selenium not working中找到相关讨论
You can find a detailed discussion in Do we have any generic function to check if page has completely loaded in Selenium
关于java - 如果加载时间太长,如何让 selenium 重新加载所需的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57468213/