Opening a new tab in the same window session of th

2019-01-26 01:14发布

问题:

How to open a new tab in the same window session of the browser through Selenium WebDriver command?

回答1:

Opening a new tab in the same browser window is possible, see solutions for Firefox:

  • How to open a new tab using Selenium WebDriver with Java?
  • Controlling firefox tabs in selenium

The problem is - once you've opened a tab, there is no built-in easy way to switch between tabs. Selenium simply doesn't provide an API for that.

Instead of a tab, open a new browser window.



回答2:

Yes you can do that , See below my sample code for that :

   //OPEN SPECIFIC URL IN BROWSER
    driver.get("http://www.toolsqa.com/automation-practice-form/");

   //MAXIMIZE BROWSER WINDWO
    driver.manage().window().maximize();


   //OPEN LINKED URL IN NEW TAB IN SAME BROWSER 
   String link1 = Keys.chord(Keys.CONTROL,Keys.ENTER); 
   driver.findElement(By.linkText("Partial Link Test")).sendKeys(link1);

Above code will open link1 in new tab. you can run above code to see effect. Above is public link includes testing form.

But as @alecxe told that there is no way to switch between tabs. So better you open new browser window.



回答3:

I am afraid, but there is a way to switch between tab's . We have successful answers for this problem.

Please find the below link.

switch tabs using Selenium WebDriver with Java



回答4:

Selenium can switch between tabs.

Python:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
element = driver.find_element_by_css_selector("html") # Gets the full page element, any element works for this
key_code = Keys.CONTROL # Use Keys.COMMAND for Mac
driver.execute_script("window.open();") # Executes Javascript to open a new tab
driver.switch_to.window(1) # Switches to the new tab (at index 1, first tab is index 0)
driver.switch_to.window(0) # Switches to the first tab


回答5:

Using java script we can easily open new tab in the same window.

public String openNewTab(){
       String parentHandle = driverObj.getWindowHandle();
        ((JavascriptExecutor)driverObj).executeScript("window.open()");
        String currentHandle ="";
                // below driver is your webdriver object
        Set<String> win  = driver.getWindowHandles();   

        Iterator<String> it =  win.iterator();
        if(win.size() > 1){
            while(it.hasNext()){
                String handle = it.next();
                if (!handle.equalsIgnoreCase(parentHandle)){
                    driver.switchTo().window(handle);
                    currentHandle = handle;
                }
            }
        }
        else{
            System.out.println("Unable to switch");
        }
        return currentHandle;
    }