如何使用 linkText 在 Selenium 中點選超連結?


頁面上的超連結由錨標記識別。要點選連結,我們可以使用匹配錨標記中包含的文字的連結文字定位器。

我們還可以使用部分連結文字定位器,它部分匹配錨標記中包含的文字。如果這兩個定位器都沒有找到匹配的元素,則會引發 NoSuchElementException。

語法

WebElement t =driver.findElement(By.partialLinkText("Refund"));
WebElement m =driver.findElement(By.linkText("Refund Policy"));

讓我們嘗試點選下面頁面上的連結退款政策 −

示例

使用 linkText 的程式碼實現

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;
public class LnkClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // identify element with link text
      WebElement m =driver.findElement(By.linkText("Refund Policy"));
      m.click();
      System.out.println("Page navigated: " + driver.getTitle());
      driver.quit();
   }
}

使用 partialLinkText 的程式碼實現

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;
public class PartialLnkClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // identify element with partial link text
      WebElement p =driver.findElement(By.partialLinkText("Refund"));
      p.click();
      System.out.println("Page navigated: " + driver.getTitle());
      driver.quit();
   }
}

輸出

更新於: 03-Apr-2021

10K+ 次觀看

開始你的職業生涯

完成課程獲得認證

開始學習
廣告