如何使用 Selenium WebDriver 打开一个新的标签页?


我们可以使用 Selenium 打开一个新标签页。Keys.chord 和 **sendKeys** 方法用于此目的。可以使用 Keys.chord 方法同时传递多个键。可以将一组字符串或键作为参数传递给该方法。

此处将 Keys.CONTROLKeys.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();
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.com/about/about_careers.htm");
      // Keys.Chord string
      String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Company']")).sendKeys(nwtb);
   }
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

更新于: 28-12-2020

1k + 人浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告