尝试让Selenium Chrome Driver刷新页面,直到找到某个项目,但所有方法都失败了

时间:2016-06-10 05:05:10

标签: java selenium selenium-chromedriver

我正在编写一个应该刷新网站的程序,直到某个项目被加载(我没有手动加载项目,但运行网站的人员),但我的方法似乎不起作用。我尝试使用FluentWait和driver.navigate()。refresh()(< - 只会刷新chromedriver浏览器一次)但是在这种情况下我知道这不是我需要的。以下是我的尝试。任何关于如何解决这个问题的指导表示赞赏!

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Washed Twill Short")));
WebElement link = driver.findElement(By.linkText("Washed Twill Short"));
driver.get(link.getAttribute("href"));

Wait<WebDriver> wait = new FluentWait(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

WebElement refresher = wait.until(new Function<WebDriver, WebElement>() 
            {
                public WebElement apply(WebDriver driver) 
                {
                    driver.navigate().refresh();    
                    return driver.findElement(By.linkText("Washed Twill Short"));           
                }
            });

Boolean isPresent = driver.findElements(By.linkText("Washed Twill Short")).size() > 0;
while(!isPresent)
            {
                driver.get(driver.getCurrentUrl());
            }

do{
   driver.navigate().refresh();
 }while(!driver.findElement(By.linkText("Washed Twil Short")).isDisplayed());

String productlink = driver.findElement(By.linkText("Washed Twill Short")).getAttribute("href");
driver.get(productlink);

1 个答案:

答案 0 :(得分:1)

你很亲密。您可以使用findElement()方法,但该方法会抛出一个会破坏正常流量的NoSuchElementException。在这种情况下,你必须用try-catch包围你的电话。

更好的方法(您也尝试过)是使用findElements()方法,如果没有匹配则返回空列表。但是你错误地放置了停止标准,只在循环之前检查一次。将支票移入循环,得到如下内容:

String url = /* some url */
driver.get(url);
while(driver.findElements(By.linkText("Washed Twill Short")).isEmpty())
{
    driver.get(url);
}