如何通过Selenium点击下拉菜单

时间:2018-04-19 07:51:09

标签: selenium selenium-webdriver drop-down-menu webdriver mousehover

Actions a= new Actions(driver);
WebElement mainmenu=driver.findElement(By.xpath(".//*[@id='yui-gen2']/a"));
a.moveToElement(mainmenu).build().perform();
WebElement Sub = driver.findElement(By.xpath(".//*[@id='helpAbout']"));    
a.moveToElement(Sub).build().perform();
Sub.click();

代码无法点击子菜单,它只是在第3行停止。

screenshot

3 个答案:

答案 0 :(得分:1)

您的代码正确率为90%,只需替换以下代码:

a.moveToElement(Sub).click().perform(); 

build()方法适用于悬停在元素上,悬停在其上后我们必须单击元素。

答案 1 :(得分:0)

鼠标悬停覆盖标识为By.xpath(".//*[@id='yui-gen2']/a")的元素,之后调用moveToElement(mainmenu)build()perform(),此阶段元素标识为By.xpath(".//*[@id='helpAbout']")可见可互动。所以你需要直接调用click(),如下所示:

Actions a= new Actions(driver);
WebElement mainmenu=driver.findElement(By.xpath(".//*[@id='yui-gen2']/a"));
a.moveToElement(mainmenu).build().perform();
WebElement Sub = driver.findElement(By.xpath(".//*[@id='helpAbout']"));    
Sub.click();

答案 2 :(得分:0)

使用硒,您应该能够执行以下操作:

Select variableName = new Select(DropDownElementLocator);
variableName.selectByVisibleText("Whatever");
// or
variableName.selectByIndex(1);