如何在 Selenium 中使用"链接文本/部分链接文本"查找元素?

seleniumautomation testingtesting tools

在 Selenium webdriver 中,我们可以使用链接文本或部分链接文本查找元素。这两个定位器只能应用于带有锚标签的元素。

链接文本定位器匹配锚标签内的文本。部分链接文本定位器匹配锚标签内的部分文本。如果没有匹配的元素,这两个定位器都会抛出 NoSuchElementException 异常。

语法

WebElement n =driver.findElement(By.partialLinkText("Coding"));
WebElement l =driver.findElement(By.linkText("Coding Ground"));

让我们在页面上找到下面突出显示的元素 CODING GROUND −

示例

Code Implementation with 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 LnkTxt{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/online_dev_tools.htm");
      // 使用链接文本标识元素
      WebElement n =driver.findElement(By.linkText("CODING GROUND"));
      n.click();
      System.out.println("Current page title : " + driver.getTitle());
      driver.quit();
   }
}

Code Implementation with 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 PartialLnkTxt{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/online_dev_tools.htm");
      // 识别包含部分链接文本的元素
      WebElement m = driver.findElement(By.partialLinkText("CODING"));
      m.click();
      System.out.println("Current page title : " + driver.getTitle());
      driver.quit();
   }
}

输出


相关文章