Selenium Webdriver:切换窗口后获取NoSuchElementException

时间:2013-07-21 11:28:10

标签: java window selenium-webdriver

I switch from window A to window B.When i try to perform an action on window B,it throws No such element exception.I am new to selenium webdriver.Please help me out.

我的要求: 1)转到http://www.kotak.com/bank/personal-banking/convenience-banking/net-banking.html 2)点击SECURELY LOGIN 3)切换到新打开的窗口并在其中填写用户名和密码。在此窗口上找到用户名和密码,抛出错误。

     My code :


    import java.util.Iterator;
    import java.util.Set;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class WindowHandler1 {


public static void main(String args[]) throws InterruptedException
{

    WebDriver driver = new FirefoxDriver();     

    driver.get("http://www.kotak.com/bank/personal-banking/convenience-                   banking/net-banking.html");
    Thread.sleep(5000);

    driver.findElement(By.xpath(".//*[@id='label-01']/a[1]")).click();
    Set<String> windowids = driver.getWindowHandles();
    Iterator<String> iter = windowids.iterator();
            System.out.println(windowids);

    String mainWindowId = iter.next();
    String tabedWindowId = iter.next();
    Thread.sleep(2000L);

            // switching to the new pop up window
            driver.switchTo().window(tabedWindowId);

            Thread.sleep(20000);

            //getting no such element exception upon executing  line below 
    driver.findElement(By.xpath(".//*[@id='Username']")).sendKeys("username");
            driver.findElement(By.id("Username")).sendKeys("abc");

} }

1 个答案:

答案 0 :(得分:0)

我有类似的问题,并注意到在selenium的窗口句柄列表中,顺序并不总是相同。因此,在您的代码中,您似乎依赖于列表中的最后一个窗口作为新窗口,而它可能是第一个窗口。解决方案是确保您尝试切换到的窗口与当前窗口句柄不同。

您可能会收到NoSuchElement异常,因为您没有在正确的窗口中。