如何在 Selenium 中使用“链接文本/部分链接文本”查找元素?
我们可以在 Selenium webdriver 中使用链接文本或部分链接文本来查找元素。这两个定位器都只能应用于使用锚标记的元素。
链接文本定位器与锚标记内的文本匹配。部分链接文本定位器与锚标记内的文本部分匹配。如果找不到匹配的元素,这两个定位器都将引发 NoSuchElementException。
语法
WebElement n =driver.findElement(By.partialLinkText("Coding"));
WebElement l =driver.findElement(By.linkText("Coding Ground"));让我们找到页面上突出显示的元素 CODING GROUND -

示例
使用 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();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/online_dev_tools.htm");
// identify element with link text
WebElement n =driver.findElement(By.linkText("CODING GROUND"));
n.click();
System.out.println("Current page title : " + 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 PartialLnkTxt{
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.com/online_dev_tools.htm");
// identify element with partial link text
WebElement m = driver.findElement(By.partialLinkText("CODING"));
m.click();
System.out.println("Current page title : " + driver.getTitle());
driver.quit();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP