如何使用 Selenium 中的属性“HTML 标签名称”查找元素?
借助定位符标签名,我们可以使用 Selenium 网页驱动程序找到元素标签名。要使用标签名定位元素,我们必须使用 By.tagName 方法。
在 HTML 代码中,标签名通常用 <> 括起来,例如,锚定标签 <a> 表示页面上的链接。输入标签表示文本框、复选框或单选按钮。我们来看看一个元素的 HTML 代码,并尝试通过其标签名对其进行识别 −

在上图中,文本“You are browsing the best resources for”具有 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();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/index.htm");
// identify element with tag name
WebElement n = driver.findElement(By.tagName("h4"));
//obtain text on element
String s = n.getText();
System.out.println("Text on element is : " + s);
driver.close();
}
}输出

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