【发布时间】:2018-06-06 23:48:57
【问题描述】:
我正在自动化 amazon.com,我目前正在尝试移动到下拉菜单中的特定元素。无论我为这个元素创建了多么具体的 xpath,WebDriver 都只会将鼠标移动到列表中的第一项。
这里是 HTML 代码:
<div class="nav-template nav-flyout-content nav-tpl-itemList">
<span class="nav-hasPanel nav-item" data-nav-panelkey="InstantVideoPanel" role="navigation" aria-label="Amazon Video">
<span class="nav-text">Amazon Video</span>
</span>
<span class="nav-hasPanel nav-item" data-nav-panelkey="DigitalMusicPanel" role="navigation" aria-label="Amazon Music">
<span class="nav-text">Amazon Music</span>
</span>
<span class="nav-hasPanel nav-item" data-nav-panelkey="AndroidPanel" role="navigation" aria-label="Appstore for Android">
<span class="nav-text">Appstore for Android</span>
</span>
这是我的自动化代码:
@Test
public void departmentsDropMusic1() throws Exception {
driver = new FirefoxDriver();
driver.get("https://www.amazon.com");
Thread.sleep(3000L);
WebElement element = driver.findElement(By.xpath("//a[@id='nav-link-shopall']"));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
Thread.sleep(3000L);
WebElement dropDown = driver.findElement(By.cssSelector("#nav-flyout-shopAll > div:nth-child(2)"));
if (dropDown.isDisplayed()) {
System.out.println("pass");
} else {
Assert.fail();
}
WebElement musicSubMenu = driver.findElement(By.xpath(//span[contains(text(), 'Amazon Music')]"));
action.moveToElement(musicSubMenu).build().perform();
Thread.sleep(3000L);
我也尝试了其他 xpath,使用 html 代码中提供的各种标签,但无济于事。 WebDriver 只会移动到第一个元素(aria-label "Amazon Video"),而不是列出的其他元素。
有趣的是,当我使用 for 循环遍历菜单中的所有项目时,没有任何问题。
【问题讨论】:
-
到底发生了什么?当您尝试将鼠标移动到其他菜单项时出现任何错误?
-
我猜是什么,有多个元素具有相同的 xpath。所以 selenium,默认情况下,鼠标悬停在具有该 xpath 的第一个标识元素(通常是 DOM 中的顶部元素)。我们可以使用 xpath 中的索引来指出 xpath 的特定出现。
-
请阅读为什么
screenshot of HTML or code or error is a bad idea。考虑使用基于格式化文本的 HTML 和代码试验来更新问题。 -
@DebanjanB -- 谢谢你让我知道和这篇文章。固定