如何使用 Selenium WebDriver 在 Chrome 浏览器的新标签页中打开链接?

seleniumautomation testingtesting tools

我们可以使用 Selenium WebDriver 的 `Keys.chord` 和 `sendKeys` 方法在 Chrome 浏览器的新标签页中打开链接。`Keys.chord` 方法用于同时发送多个按键作为参数。

要打开一个新标签页,需要将 `Keys.CONTROL` 和 `Keys.ENTER` 作为参数传递给 `Keys.chord`。最后,将 `Keys.chord` 作为参数传递给 `sendKeys`。

让我们点击下图中高亮显示的"Jobs"链接,在新标签页中打开链接。

语法

String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath ("//a[@title='Job @ Tutorials Point']")).sendKeys(l);

示例

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 org.openqa.selenium.Keys;
public class ElementLocator{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/index.htm");
      //Keys.chord string
      String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
      //在新标签页中打开
      driver.findElement(By.xpath ("//a[@title='Job @ Tutorials Point']")).sendKeys(l);
   }
}

输出


相关文章