2015-05-04 45 views
4

我只是想知道是否有一个优雅的方式来利用ExpectedConditions或其他东西让我的代码等待页面的源代码包含给定的字符串,直到给定的超时。我知道我可以使用这样的事情,如果我想使用的特定元素的定位...Selenium等待页面源代码包含

WebDriverWait wait = new WebDriverWait(driver,10); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("foobar"))); 

,但我想做到这一点,而无需使用定位特定元素,只是使用整个网页源代码我的参考而已。有什么建议么?

+0

你对“整个页面源”有什么意义?你想如何设定一个条件?礼物? – swinkler

+0

@swinkler是啊只是HTML目前 – user2150250

+0

但是,是一个元素将与By.ByTagName – swinkler

回答

2

你不能拥有所有元素作为等待的条件。当切换页面weddriver自动等待页面加载。当它完成加载HTML元素时,它会继续。但它不等待JavaScript执行。现在很多网页使用JavaScript在HTML加载后填充网页。

你应该做的是等待你想要使用的每个元素。

wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOfElementLocated(by))); 

wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(element))h; 
+0

为什么'.refreshed()'是必需的? – dialex

+0

它刷新搜索元素的dom –

0

不取决于知名度,你可以检查一个元素是否存在于DOM:

WebDriverWait wait = new WebDriverWait(driver,10); 
wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("html"))); 

如果你想指个人的文字,就可以实现ExpectedCondition<T>并创建自己的条件类。所提到的接口可以访问WebDriver(由于超级接口com.google.common.base.Function<WebDriver,T>)。

apply您可以使用WebDriver,并调用方法getPageSource()方法有String呈现页面的源代码。检查String你喜欢什么。

+0

我相信方法名是'By.tagName'。 – LittlePanda

+0

更正。谢谢 – swinkler

0

可以等待文件的readyState成为complete。针对正在加载的网页运行javascript return document.readyState").equals("complete")

void waitForLoad(WebDriver driver) { 
    ExpectedCondition<Boolean> pageLoadCondition = new 
     ExpectedCondition<Boolean>() { 
      public Boolean apply(WebDriver driver) { 
       return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete"); 
      } 
     }; 
    WebDriverWait wait = new WebDriverWait(driver, 30); 
    wait.until(pageLoadCondition); 
} 

然后你就可以得到网页源:

driver.getPageSource(); 

然后验证pageSource包含你在找什么:

driver.getPageSource().contains("your element/tag"); 

我希望这有助于!

+0

正如我在我的答案中所述。这只会等待HTML元素在完全加载时出现在页面上。之后添加的任何元素都将无法从webdriver –

+0

如何使用scriptTimeout?这是否等待Ajax的东西? – LittlePanda

+0

你不想等待alla JavaScripts完成。其中一些可能永远不会完成。 –