如何使用 Selenium WebDriver 在新標籤中開啟連結?


我們可以使用 Selenium 在新標籤中開啟一個連結。方法 Keys.chordsendKeys 可以用於此目的。Keys.chord 方法允許你同時傳遞多個鍵。

我們應傳送 Keys.CONTROLKeys.ENTER 作為引數給 Keys.chord 方法。然後,完整字串作為引數傳遞給 sendKeys 方法。最後,sendKeys 方法必須應用於透過 driver.findElement 方法識別的連結。

語法

String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Privacy Policy']")). sendKeys(clicklnk);

示例

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 OpenInNwTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // Keys.Chord string
      String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Privacy Policy']")).sendKeys(clicklnk);
   }
}

輸出

更新於: 30-11-2020

9 千+ 瀏覽量

開啟你的職業生涯

完成課程認證

立即開始
廣告