如何使用 Selenium WebDriver 打开新标签页?
seleniumautomation testingtesting tools
我们可以使用 Selenium 打开新标签页。为此,可以使用 `Keys.chord` 和 `sendKeys` 方法。`Keys.chord` 方法可以同时传递多个按键。可以将一组字符串或按键作为参数传递给该方法。
这里,`Keys.CONTROL` 和 `Keys.ENTER` 作为参数传递给 `Keys.chord` 方法。它们会被存储为字符串值,并最终作为参数传递给 `sendKeys` 方法。
语法
String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Company']")).sendKeys(nwtb);
示例
代码实现。
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;
public class OpnLinkNwTab{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// 等待 4 秒
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// Keys.Chord 字符串
String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);
// 在新标签页中打开链接,Keys.Chord 字符串传递给 sendKeys
driver.findElement(
By.xpath("//*[text()='Company']")).sendKeys(nwtb);
}
}
输出


