如何在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