How to open a link in new tab (chrome) using Selenium WebDriver?

后端 未结 14 2546
余生分开走
余生分开走 2020-11-30 03:37
System.setProperty(\"webdriver.chrome.driver\", \"D:\\\\softwares\\\\chromedriver_win32\\\\chromedriver.exe\");

WebDriver driver = new ChromeDriver();
driver.manage         


        
14条回答
  •  余生分开走
    2020-11-30 04:08

    Selenium can only automate on the WebElements of the browser. Opening a new tab is an operation performed on the webBrowser which is a stand alone application. For doing this you can make use of the Robot class from the java.util.* package which can perform operations using the keyboard regardless of what type of application it is. So here's the code for your operation. Note that you cannot automate stand alone applications using the Robot class but you can perform keyboard or mouse operations

    System.setProperty("webdriver.chrome.driver","softwares\\chromedriver_win32\\chromedriver.exe"); 
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("http://www.google.com");
    Robot rob = new Robot();
    rob.keyPress(keyEvent.VK_CONTROL);
    rob.keyPress(keyEvent.VK_T);
    rob.keyRelease(keyEvent.VK_CONTROL);
    rob.keyRelease(keyEvent.VK_T);
    

    After this step you will need a window iterator to switch to the new tab:

    Set  ids = driver.getWindowHandles();
    Iterator  it = ids.iterator();
    String currentWindow = it.next();
    String newWindow = it.next();
    driver.switchTo().window(newWindow);
    driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);
    

提交回复
热议问题