无法使用Selenium Gecko WebDriver导航到URL

时间:2018-04-13 01:36:00

标签: java eclipse selenium selenium-webdriver geckodriver

我今天发生了这个有趣的错误。我已经使用Selenium多年了,从来没有遇到导航到URL的问题(通过driver.navigate().to(url))但是今天我尝试导航到特定的URL并且我发现在执行程序之后几个有时它只会停留在原始页面而不导航到新页面。

有趣的是,这只发生在大约50%的时间,并且只有在程序的特定部分导航到特定URL时才会发生(在程序的其他部分我没有问题导航到此URL)。

当前页面上的某些元素是否可能阻止driver.navigate().to(url)执行?

我已查看thisthis问题,但两者似乎都存在完全导航问题。在我的情况下,它有时是有效的,有时也不起作用(即使使用完全相同的URL)。

此外,我没有收到任何具体错误(因此我没有更多信息要发布)。该程序只是继续进行,就像声明不存在一样。

如果有必要,我很乐意提供其他详细信息。

代码:

shoppingCartURL.navToShoppingCart(driver);

String[] XPath = { "//*[contains (@value,'Delete')]" };

List<WebElement> elementList = webElementX.getElementListByXPath(driver, XPath);

System.out.println("Deleting " + elementList.size() + " element(s) from shopping cart");

for (int elementListCounter = 0; elementListCounter < elementList.size(); elementListCounter++) {

    WebElement singleElement = elementList.get(elementListCounter);

    try {
        singleElement.click();
    } catch (Exception e) {

        System.out.println("Exception occurred (StaleElementReferenceException)");
    }

}

if (conditionX == false) {
    productPage.navToProductPage(driver, product); // this method is not always executed, program continues to execute productPage.performActionOnPage(driver); without navigating to 'product page'
    productPage.performActionOnPage(driver);
}




public void navToProductPage(WebDriver driver, String product)

{
   String URL = "https://www.example.com/product/" + product;
   System.out.println("Navigating to " + URL); // always prints the  correct url (but still doesn't always navigate to url as mentioned in question)
   driver.navigate().to(URL);

}

更新:

我在重定向网址中注意到ref=cart-ajax-error(从购物车中删除商品后)。显然,该网站在从购物车中删除商品后使用AJAX刷新页面。我试图导航到另一个页面可能会发生这种冲突吗? 换句话说,也许Selenium会同时收到两条不同的消息。刷新页面并导航到新页面..所以它仍保留在当前页面上?

如果这是真的,可以采取哪些措施来解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

当它有时会发生时,有时并不是时间问题。

导航到URL后,在代码中添加显式等待:

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.urlToBe(URL));