如何在 Selenium 中使用 linkText 点击超链接?

seleniumautomation testingtesting tools

页面上的超链接用锚标签标识。要点击链接,我们可以使用链接文本定位器,​​该定位器与锚标签内的文本匹配。

我们也可以使用部分链接文本定位器,​​该定位器与锚标签内的文本部分匹配。如果这两个定位器都找不到匹配的元素,则会抛出 NoSuchElementException。

语法

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

让我们尝试点击以下页面上的"退款政策"链接 −

示例

使用链接文本的代码实现

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();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // 使用链接文本标识元素
      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();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // 用部分链接文本标识元素
      WebElement p =driver.findElement(By.partialLinkText("Refund"));
      p.click();
      System.out.println("Page navigated: " + driver.getTitle());
      driver.quit();
   }
}

输出


相关文章