在新选项卡Selenium中打开下拉菜单选项

时间:2018-08-02 10:26:10

标签: java selenium-webdriver

它会在同一选项卡中打开。我想重定向到下一个标签页或下一个窗口。

代码:

try
{   
    for(int i=1;i<=9;i++)
    {
        if(i==1)
        {
            System.out.println("No Condition applied");
        }
        else if(i==2)
        {
            WebElement menu2=driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div/ul/li["+i+"]/a"));
            Actions action=new Actions(driver);
            //It opens in same page
            action.moveToElement(menu2).moveToElement(driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div/ul/li[2]/ul/li["+i+"]/a"))).click().build().perform();
            //mouse hover on selected drop down
            action.moveToElement(menu2).moveToElement(driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div/ul/li[2]/ul/li["+i+"]/a"))).build().perform();
            //Should open in New Tab-But Not working
            action.moveToElement(menu2).moveToElement(driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div/ul/li[2]/ul/li["+i+"]/a"))).sendKeys(Keys.CONTROL).sendKeys(Keys.ENTER).build().perform();
        }
    }
}
catch(Exception e)
{
    System.out.println("Menu button not found");
}

1 个答案:

答案 0 :(得分:0)

您可以为此使用Actions

WebElement element = driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div/ul/li[2]/ul/li["+i+"]/a"));
Actions action = new Actions(driver);
action.keyDown(Keys.SHIFT).click(element).keyUp(Keys.SHIFT).build().perform();

请注意,请勿使用绝对的xpath,因为它很脆弱。尝试尽可能使用id / class属性。