如何使用 WebDriver(Selenium 2)檢查 DOM 是否具有類?
我們可以用 Selenium webdriver 檢查 DOM 是否具有類。我們可以使用 findElements 方法來獲取具有特定類的元素列表。然後將 By.className 或 By.xpath 或 By.cssSelector 作為引數傳遞給該方法。
我們將要搜尋的類名作為引數傳遞給該方法。讓我們研究下面的 html 程式碼以瞭解具有類值 toc chapters 的 ul 元素。然後獲取其子元素。
示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ClassAttrb{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://tutorialspoint.tw/about/about_careers.htm"); // identify element with class attribute WebElement m= driver.findElements(By.xpath("//ul[@class='toc chapters']")); //identify children List<WebElement> ch = m.findElements(By.xpath("./child::*")); // iterate through sub elements for ( WebElement i : ch ) { // get text for children System.out.println(i.getText()); } driver.close(); } }
輸出
廣告