如何在 Selenium 中提取元素的属性值?
借助 getAttribute() 方法,我们可以在 Selenium 中提取元素的属性值。找到元素后,使用此方法来获取元素的属性值并分配给一个变量。
示例
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; import java.util.List; public class AttributeType { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); //Using id tagname attribute combination for css expression WebElement button = driver.findElement(By.cssSelector("input[name=’search’]")); // getting the type attribute and printing in console String buttontype = button.getAttribute(“type”); System.out.println(“Attribute value is “ + buttontype); driver.close(); } }
广告