如何在同一个浏览器中打开新标签页并在它们之间切换,使用Selenium?
我们可以使用Selenium webdriver在同一个浏览器中打开新的标签页并在它们之间切换。首先,要在同一个浏览器中打开一个新的标签页,我们需要借助Keys.chord和sendKeys方法。
Keys.CONTROL和Keys.ENTER参数传递给Keys.chord方法。此方法产生一个字符串值,并作为参数传递给sendKeys方法。
语法
String n = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.id("open-tab")).sendKeys(n);打开第二个标签页后,getWindowHandles方法用于在一个Set中保存所有窗口句柄ID。为了将webdriver对象的焦点切换到新标签页,使用switchTo().window方法。
新标签页的窗口句柄ID应作为参数传递给switchTo().window,以将驱动程序焦点切换到新标签页。getWindowHandle方法用于获取当前焦点浏览器窗口的窗口句柄ID。
让我们在一个新的浏览器标签页中打开“团队”链接:

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.Keys;
import java.util.ArrayList;
public class SwitchNewTab{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// method Keys.chord
String n = Keys.chord(Keys.CONTROL, Keys.ENTER);
//open link in new tab
driver.findElement(By.linkText("Team")).sendKeys(n);
Thread.sleep(8000);
// store window handle ids
ArrayList<String> w = new ArrayList<String>(driver.getWindowHandles());
//switch to open tab
driver.switchTo().window(w.get(1));
System.out.println("New tab title: " + driver.getTitle());
//switch to first tab
driver.switchTo().window(w.get(0));
System.out.println("First tab title: " + driver.getTitle());
driver.quit();
}
}输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP