如何在 Selenium 中使用"HTML 标签名称"属性查找元素?
seleniumautomation testingtesting tools
我们可以使用 Selenium webdriver 中的定位器 tagname,通过元素标签名称查找元素。要通过标签名称定位元素,我们必须使用 By.tagName 方法。
在 HTML 代码中,标签名称通常用 <> 括起来,例如,锚标签 <a> 表示页面上的链接。输入标签表示文本框、复选框或单选按钮。让我们查看元素的 HTML 代码,并尝试通过其标签名称 − 来识别它。

在上图中,文本 –您正在浏览具有 h4 标签的最佳资源。
语法
WebElement e = driver. findElement(By.tagName("h4"));
示例
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 LocatorTagName{
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/index.htm");
// 通过标签名识别元素
WebElement n = driver.findElement(By.tagName("h4"));
// 获取元素上的文本
String s = n.getText();
System.out.println("Text on element is : " + s);
driver.close();
}
}
输出


