如何使用webdriver关闭网页上的弹出窗口

时间:2015-09-14 21:38:28

标签: java selenium web webdriver driver

<在此处插入问题。>

public class Day4
{
    @Test
    public void main() throws InterruptedException
    {
        WebDriver Driver = new FirefoxDriver();
        Driver.get("http://live.guru99.com");
        Driver.manage().window().maximize();
        Thread.sleep(6000);
        WebElement element = Driver.findElement(By.xpath("//a[text()='Mobile']"));
        element.click();
        element = Driver.findElement(By.xpath("//a[text()='IPhone']/../../div[@class='actions']//a[text()='Add to Compare']"));
        Thread.sleep(2000);
        element.click();
        element = Driver.findElement(By.xpath("//a[text()='Samsung Galaxy']/../../div[@class='actions']//a[text()='Add to Compare']"));
        Thread.sleep(2000);
        element.click();
        element = Driver.findElement(By.xpath("//button[@title='Compare']"));
        element.click();
        element = Driver.findElement(By.xpath("//button[@title='Close Window']"));
        Thread.sleep(6000);
        element.click();
        Set<String> windowId = Driver.getWindowHandles(); // get window id of current window
        Iterator<String> itererator = windowId.iterator();

        String mainWinID = itererator.next();
        String newAdwinID = itererator.next();

        Driver.switchTo().window(newAdwinID);
        System.out.println(Driver.getTitle());
        Thread.sleep(3000);
        Driver.close();

        Driver.switchTo().window(mainWinID);
        System.out.println(Driver.getTitle());
        Thread.sleep(2000);

        Driver.close();
    }
}

1 个答案:

答案 0 :(得分:0)

我检查了你的代码,发现下面的元素不存在

element = Driver.findElement(By.xpath("//button[@title='Close Window']"));

我删除了该代码,现在弹出窗口工作正常: -

 element = Driver.findElement(By.xpath("//button[@title='Compare']"));
 element.click();
 Set<String> windowId = Driver.getWindowHandles(); // get window id of current window
 Iterator<String> itererator = windowId.iterator();

 System.out.println(itererator);
 String mainWinID = itererator.next();
 String newAdwinID = itererator.next();

 Driver.switchTo().window(newAdwinID);

 Driver.close();

希望它会对你有所帮助:)。