4

I want to open a website with selenium and extract some text via xpath. It's working but I can get the text only if I wait a few seconds until the whole website is loaded, but it would be nicer to check if the website is fully loaded. I guess I should check for any background connections (ajax calls, GETs, POSTs or whatever), what is the best way to do it? At the moment I'm trying to extract the text in a while loop (ugly solution):

WebDriver driver = new FirefoxDriver();
driver.get("http://www.website.com");


// Try to get text
 while (true) {
   try {
     WebElement findElement = driver.findElement(By.xpath("expression-here"));
     System.out.println(findElement.getText());
     break;
// If there is no text sleep one second and try again
   } catch (org.openqa.selenium.NoSuchElementException e) {
     System.out.println("Waiting...");
     Thread.sleep(1000);
   }
 }

How would you solve this?

4

2 回答 2

3

Selenium has already timeouts for this.

Look here: http://seleniumhq.org/docs/04_webdriver_advanced.jsp

I have solve it with:

webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
于 2012-12-27T00:08:32.457 回答
2

更喜欢显式等待:
1)更具可读性
2)已经使用了很长时间
3)如果您知道该元素不存在(您的测试是验证它)并且不需要轮询 10 秒怎么办?使用隐式你现在正在浪费时间。

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
        return d.findElement(By.id("myDynamicElement"));
    }});
于 2012-12-27T12:35:57.463 回答