在 Selenium Webdriver 中查詢子元素中的元素。
我們可以使用 Selenium webdriver 在子元素中查詢元素。首先,我們需要使用任何定位符(如 id、class、name、xpath 或 css)來識別元素。然後,我們必須使用 findElements(By.xpath()) 方法識別子元素。
我們可以透過將其與元素本地化並然後將表示式 (./child::*) 作為引數傳遞給 findElements(By.xpath()) 來識別元素中的子元素
語法
element.findElements(By.xpath("./child::*"))
讓我們在以下 html 程式碼中識別元素 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 SubElement{ 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 WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']")); //identify sub-elements with ./child::* expression in xpath List c = t.findElements(By.xpath("./child::*")); // iterate sub-elements for ( WebElement i : c ) { //getTagName() to get tag of sub-elements System.out.println(i.getTagName()); } driver.close(); } }
輸出
廣告