如何使用 Selenium 遍历网页上的菜单列表?
seleniumautomation testingtesting tools
我们可以使用 Selenium WebDriver 遍历网页上的菜单列表。
在网页中,列表由 `ul` 标签表示,它包含 `li` 标签的子元素。因此,`li` 标签可以被视为 `ul` 的子元素。
首先,我们需要使用定位器找到 `ul` 标签的元素,然后使用循环遍历其 `li` 子元素。最后,使用 `getText` 方法获取 `li` 元素中的文本。
让我们尝试找到网页上的菜单列表。

示例
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;
import java.util.List;
public class MenuItemLst{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//隐式等待
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL 启动
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// 使用 findElements 函数识别菜单中的元素
List<WebElement> p = driver.
findElements(By.xpath("//ul[@class='toc reading']/li"));
System.out.println("Menu Items are: ");
//遍历列表
for( WebElement i: p){
System.out.println(i.getText());
driver.quit();}
}
}
}
输出


