Selenium WebDriver: Open new tab instead of a new window

邮差的信 提交于 2020-01-19 05:11:06

问题


I am using Selenium WebDriver. Every link is opened in a new browser window. It is not convenient for me. How can I change it so that it opens just in new tab?


回答1:


Selenium has no ability to switch tabs at the moment. Because of this we force the browser to open links in new windows but since we are able to switch windows we force the browser to take the approach. This may be fixed in a later version




回答2:


Selenium has the ability to switch over tabs now-a-days. The below code1: will work for firefox, code2: for IE and chrome by using Robot class we can do and the control doesnt move automatically to current tab so we need to switch to the current tab by using window handles method. The given below code will work well When we are running individual script but when running as a suite you may feel the pain in performing key board events. In order to avoid that we got to go with other possibility by using user defined javascript method by using javascript executor in selenium-Java.

We can switch between windows and tabs by identifying its name allocated for each and every windows which we open and the name will be in alphanumeric character.

    ***Code 1***
    //First tab(default tab)
    driver.navigate().to("http://www.google.com");
    driver.manage().window().maximize();

    //second tab
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
    driver.navigate().to("https://yahoo.com");

    //third tab
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
    driver.navigate().to("http://www.google.com");

    //move to very first tab.
    driver.findElement(By.cssSelector("body"))
            .sendKeys(Keys.CONTROL + "\t");

    // To close the current tab.    
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
    **code 2**
    driver.navigate().to("http://www.google.com");
    driver.manage().window().maximize();


    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_T);

    Set<String> handles = driver.getWindowHandles();
    List<String> handlesList = new ArrayList<String>(handles);
    String newTab = handlesList.get(handlesList.size() - 1);

    // switch to new tab
    driver.switchTo().window(newTab); 
    driver.get("http://www.yahoo.com");


来源:https://stackoverflow.com/questions/11358316/selenium-webdriver-open-new-tab-instead-of-a-new-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!