在 Selenuim 中開啟新瀏覽器標籤


答案 - 我們可以在 Selenium WebDriver 中開啟一個新的瀏覽器標籤。需要使用 Keys.chord 方法和 sendKeys 方法來實現此任務。Keys.chord 方法用於一次傳送多個按鍵。

我們應該將 Keys.CONTROL 和 Keys.ENTER 作為引數傳遞給該方法。完整的字串又作為引數傳遞給 sendKeys。最後,sendKeys 方法應該應用於我們希望在新標籤中開啟的連結

語法

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

程式碼實現

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class OpenNewTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
      "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //url launch
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // Keys.Chord string
      String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open new tab
      driver.findElement(By.xpath("//*[text()='Terms of Use']")).sendKeys(l);
   }
}


更新時間: 2021-06-29

534 次瀏覽

開啟你的職業生涯

完成課程並獲取認證

開始
廣告