如何使用 Selenium WebDriver 在 Chrome 瀏覽器的新的標籤頁中開啟一個連結?


我們可以使用 Selenium webdriver 開啟 Chrome 瀏覽器新標籤頁中的連結,方法是使用 Keys.chord 方法和 sendKeys 方法。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();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://tutorialspoint.tw/index.htm");
      //Keys.chord string
      String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
      //open in a new tab
      driver.findElement(By.xpath ("//a[@title='Job @ Tutorials Point']")).sendKeys(l);
   }
}

輸出

更新於: 06-04-2021

2K+ 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告