如何使用 Selenium 中的“id”属性查找元素?
在 Selenium 网页驱动程序中,我们可以使用定位器来查找具有属性 id 的元素——id、css 或 xpath。要通过 css 识别元素,表达方式应该是 tagname[id='value'],要使用的方法是 By.cssSelector。
要通过 xpath 识别元素,表达方式应该是 //tagname[@id='value']。然后,我们必须使用 By.xpath 方法来定位它。要根据 id 定位器定位元素,我们必须使用 By.id 方法。
让我们看看具有 id 属性的元素的 html 代码——

语法
WebElement e = driver. findElement(By.id("session_key"));
WebElement m = driver. findElement(By.xpath("//input[@id=' session_key']"));
WebElement n =
driver. findElement(By.cssSelector("input[id=' session_key']"));示例
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 LocatorId{
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://www.linkedin.com/");
// identify element with Id
WebElement l = driver.findElement(By.id("session_key"));
l.sendKeys("Java");
//identify element with css
WebElement m = driver.
findElement(By.cssSelector("input[id='session_key']"));
String s = m.getAttribute("value");
System.out.println("Attribute value: " + s);
//identify element with xpath
WebElement n = driver.
findElement(By.xpath("//input[@id='session_key']"));
n.clear();
driver.quit();
}
}输出

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