如何在Selenium中使用"name"属性查找元素?
我们可以使用具有定位符名称、css或xpath的Selenium webdriver通过属性名称查找元素。要使用css识别元素,表达式应为tagname[name='value'],要使用的方法为By.cssSelector。
要使用xpath识别元素,表达式应为 //tagname[@name='value'].然后,我们必须使用By.xpath方法定位它。要使用定位符名称定位元素,我们必须使用By.name方法。
让我们看看具有name属性的元素的html代码 -

语法
WebElement e = driver. findElement(By.name("q"));
WebElement m = driver. findElement(By.xpath("//input[@name = 'q']"));
WebElement n =
driver. findElement(By.cssSelector("input[name='q']"));示例
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 LocatorName{
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.google.com/");
// identify element with name
WebElement k = driver.findElement(By.name("q"));
k.sendKeys("Selenium");
//identify element with css
WebElement p = driver.
findElement(By.cssSelector("input[name='q']"));
String st = p.getAttribute("value");
System.out.println("Attribute value: " + st);
//identify element with xpath
WebElement o = driver.
findElement(By.xpath("//input[@name='q']"));
o.clear();
driver.quit();
}
}输出

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