如何使用 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.com/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.com/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();
}
}输出

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