鼠标悬停功能使用selenium Webdriver

时间:2014-10-09 03:42:59

标签: java selenium selenium-webdriver mousehover

我想将鼠标悬停在图像图标上,然后显示下拉列表,以便从下拉列表中单击第一个选项。

我尝试了所有这些选项但不适用于我。请建议

    Actions act = new Actions(driver);
    WebElement iconhover =driver.findElement(By.className("insertItems"));
    act.moveToElement(iconhover).click().build().perform();
    WebElement ModulesAndTopics = driver.findElement(By.xpath("//*[@title='Topics']"));
    ModulesAndTopics.click();

另一次尝试

driver.switchTo().window(subwindow);
WebElement element = driver.findElement(By.className("insertItems"));
Locatable hoverItem = (Locatable) element;
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseMove(hoverItem.getCoordinates());

4 个答案:

答案 0 :(得分:0)

您需要将鼠标悬停在下拉列表上并执行点击。

Actions act = new Actions(driver);
WebElement iconhover =driver.findElement(By.className("insertItems"));
act.moveToElement(iconhover).click().build().perform();
WebElement ModulesAndTopics = driver.findElement(By.xpath("//*[@title='Topics']"));
act.moveToElement(ModulesAndTopics).click().build().perform();   //hover and click

答案 1 :(得分:0)

请尝试这个,如果没有解决您的问题,那么请提供您的HTML,所以我可以检查:

new Actions(driver).
    moveToElement(driver.findElement(By.className("insertItems")))
      .build().perform();
    Thread.sleep(2000);
    //If //*[@title='Topics'] is xpath of your dropdown select tag
    Select sel=new Select(wd.findElement(By.xpath("By.xpath("//*[@title='Topics']")")));
    sel.selectByIndex(Index_OF_Option);

答案 2 :(得分:0)

我认为你正在处理一个菜单项。我假设className =“insertItems”是唯一的。

//Locate the image icon
WebElement iconhover = driver.findElement(By.className("insertItems"));

//Hover mouse above the image icon - **DONT click**
Actions builder = new Actions(driver);
builder.moveToElement(iconhover).build().perform();

//Locating the first menu item - *plz use tagname instead of * in xpath* as its preferable
WebElement modulesAndTopics = driver.findElement(By.xpath("//*[@title='Topics']"));
modulesAndTopics.click();

请注意,有时下拉列表需要一些时间才能打开,因此建议在查找菜单项时使用显式等待 - “modulesAndTopics”,如下所示:

WebDriverWait wait = new WebDriverWait(driver,10);
WebElement modulesAndTopics = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@title='Topics']")));
modulesAndTopics.click();

答案 3 :(得分:0)

请尝试以下代码,似乎您还没有使用过Select class:

WebElement iconhover = driver.findElement(By.className("insertItems"));       
Actions builder = new Actions(driver);    
builder.moveToElement(iconhover).build().perform();    
WebElement abc=driver.findElement(By.xpath("//*[@title='Topics']");    
Select drop= new Select(abc);    
drop.selectByVisibleText("xyz");