如何在 Selenium Webdriver 中獲取某個元素的屬性值?
我們可以獲得元素在 Selenium Webdriver 中的屬性值。這透過 getAttribute 方法實現。在 html 文件中,每個元素透過其標籤名稱以及帶值的元素屬性進行標識。要獲取屬性值,我們必須將元素屬性作為引數傳遞給 getAttribute 方法。
讓我們看看一個元素的 html 程式碼並獲得其 src 屬性的值。其 src 屬性的值應為 /about/images/logo.png。
示例
程式碼實現。
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class AttributeVal{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //application launch driver.get("https://tutorialspoint.tw/about/about_careers.htm"); // identify element WebElement l=driver.findElement(By.className("tp-logo")); // getAttribute() to get src value String value = l.getAttribute("src"); System.out.println("Src attribute is: "+ value); //browser close driver.close() } }
輸出
廣告