如何在Selenium中使用“類名”屬性查詢元素?
我們可以使用類名屬性和Selenium webdriver以及定位器——類名、css或xpath來查詢元素。要使用css識別元素,表示式應為tagname[class='value'],使用方法為By.cssSelector。
要使用xpath識別元素,表示式應為//tagname[@class='value']。然後,我們必須使用方法By.xpath來定位它。要使用定位器類名定位元素,我們必須使用方法By.className。
讓我們來看一下具有class屬性的元素的html程式碼:
語法
WebElement e = driver. findElement(By.className("input")); WebElement m = driver. findElement(By.xpath("//input[@class = 'input']")); WebElement n = driver. findElement(By.cssSelector("input[class='input']"));
示例
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 LocatorClsName{ 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.tw/videotutorials/subscription.php"); // identify element with class WebElement n = driver.findElement(By.className("input")); n.sendKeys("JavaScript"); //identify element with cssSelector WebElement n = driver. findElement(By.cssSelector("input[class='input']")); String str = n.getAttribute("value"); System.out.println("Attribute value is : " + str); //identify element with xpath WebElement p = driver. findElement(By.xpath("//input[@class='input']")); p.clear(); driver.close(); } }
輸出
廣告