当元素已经存在时,如何停止在Selenium WebDriver中加载页面? [英] How to stop loading page in Selenium WebDriver when an element is already present?

查看:801
本文介绍了当元素已经存在时,如何停止在Selenium WebDriver中加载页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要抓取一个网站,由于某种原因,它需要15秒才能加载,但是我需要的元素在最初的5秒钟内就可以加载了.

I'm scraping a website, which for some reason takes 15 seconds to load, but the elements I need get loaded in the first 5 seconds.

问题是,我可以停止加载页面,并在已有代码的情况下继续使用代码吗?

The question is, can I stop loading a page, and move on with the code when the code is already present?

driver.Navigate().GoToUrl(url);

new WebDriverWait(driver, TimeSpan.FromSeconds(20))
    .Until(ExpectedConditions.ElementIsVisible(By.XPath(xpath)));

当前行为:

  1. 我打电话给driver.Navigate().GoToUrl(url);
  2. 驱动程序开始加载页面
  3. 该元素的存在范围约为. 5秒钟(那是我要转到下一条语句的时间)
  4. 驱动程序等待整个15秒钟来完全加载页面
  5. 然后,驱动程序最终移至WebDriverWait功能
  1. I call driver.Navigate().GoToUrl(url);
  2. The driver starts loading the page
  3. The element is present within approx. 5 seconds (that's when I want to move on to the next statement)
  4. The driver waits for the whole 15 seconds to fully load the page
  5. Then the driver finally moves to the WebDriverWait function

问题:

页面完全加载后,将调用所有类似问题的解决方案,从而使答案无用.

The problem:

All of the solutions in similar questions are called after the page fully loaded, making the answer useless.

我可以做些什么吗?谢谢.

Can I do something about it? Thank you.

推荐答案

方法.Navigate().GoToUrl的创建方式是仅在页面完全加载后才执行下一行.因此,是的,您编写的代码无关紧要,导航方法之后,直到页面完全加载后它才起作用. 作为一种解决方法,您可以选择timeout选项,此选项将在页面仍要加载时抛出异常,因此我们应捕获该异常并执行我们的下一个代码.

Method .Navigate().GoToUrl is created such a way that next line is executed only when page gets fully loaded. so yes, it doesn't matter what you are writing in code, after navigate method, it will never work until the page gets fully loaded. As a workaround you can opt for timeout option, with this it will throw a exception as page remains to load so we should catch that and execute our next code.

//这是Java代码,因此请仅从此处选择逻辑:
//将页面加载超时设置为10秒.

//This is java code, so please pick only the logic from here:
// Set the page load timeout to 10 seconds.

driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);  

try {  
  driver.Navigate().GoToUrl(url);  
} catch (TimeoutException e) {  
  // Ignore the exception.  
}  

这篇关于当元素已经存在时,如何停止在Selenium WebDriver中加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆