我无法使用Java中的selenium webdriver获取walmart主页下拉框的xpath

时间:2016-01-21 19:13:34

标签: java selenium xpath selenium-webdriver webdriver

我正在尝试使用selenium webdriver在java中编码,点击walmart页面中的下拉列表。但是我无法访问li元素。

<button class="js-flyout-toggle dropdown" aria-haspopup="true" type="button" data-cat-id="0" aria-expanded="false"> All </button>
<div class="js-flyout-modal flyout-modal">
<ul class="block-list">
<li><button class="no-margin font-semibold" type="button" data-cat-id="0" tabindex="-1"> All Departments </button></li>
<li><button class="no-margin font-semibold" type="button" data-cat-id="91083" tabindex="-1"> Auto & Tires </button></li>
<li><button class="no-margin font-semibold" type="button" data-cat-id="5427" tabindex="-1"> Baby </button></li>

我想在Java中使用selenium webdriver访问Baby。 以下是我的代码:

driver.get("http://www.walmart.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement dropdown = driver.findElement(By.xpath("html/body/div[2]/header/div[3]/div/div/div/div/div[3]/form/div/div[1]/div/button"));
dropdown.click();
List<WebElement> liElements = driver.findElements(By.xpath("//*[@class='block-list']/li"));
for ( WebElement we: liElements) { 
    System.out.println(we.getText());           
            }

但是这会产生如下错误: -

  

“线程中的异常”主“   org.openqa.selenium.ElementNotVisibleException:元素不是   目前可见,因此可能无法与命令持续时间进行交互   或超时:132毫秒“。

请帮忙

3 个答案:

答案 0 :(得分:0)

您定义了WebDriverWait,但您没有使用它

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement dropdown = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("dropdown")));

隐式等待会在DOM中等待元素存在。如果您想使用显式等待,您还需要使用Expected Conditions。仅定义WebDriverWait实际上并没有做任何事情。

答案 1 :(得分:0)

您的代码看起来很好。请在xpath下面尝试: -

//div[@class='js-flyout-modal flyout-modal']//ul[@class='block-list']/li

现在首先尝试将thread.sleep置于其中,然后才会出现问题

Thread.sleep(30000);

但是不要为你的脚本使用Thread,因为它不推荐..这只是为了确保脚本因时间而失败

希望它会对你有所帮助:)。

答案 2 :(得分:0)

可能是walmart页面中的其他元素与您的xpath //*[@class='block-list']/li匹配,并且该元素不可见。