获取所有链接 under/in 一个特定的 class-selenium webdriver (java)

fetch all links under/in a specific class-selenium webdriver (java)

有没有办法获取特定 class 下的所有链接?

问题是,我正在编写一个测试,要求我点击一个随机 item/product,但是如果通过 By.tagName("a") 创建一个包含所有链接的列表,它将获取所有页面上的链接。更确切地说,考虑this website,现在我想随机选择pretsummer saleaccessoriesbt lawn'16sale, lookbook 或点击 summer sale 后,我想随机点击其下的其中一个产品。知道怎么做吗?

这是我的程序片段:

如果您想 select 您提到的站点中的所有 classes,请使用以下 xpath:

List<WebElement> allMenus = driver.findElements(By.xpath(".//a[contains(@class, 'level0')]"));

然后循环 WebElements 以找到所需的菜单项。此外,还观察到在鼠标悬停在特定项目上后会显示子菜单项。要执行鼠标悬停操作,我们必须使用 Actions class。请找到以下代码供您参考。

Actions mouseHovers = new Actions(driver);
// Looping through the menu items stored in the above list variable
for(WebElement eachMenu : allMenus) {
    mouseHovers.moveToElement(eachMenu).perform();
    // Select the desired sub-menu by using the above line of code by replacing the "eachMenu" element with the respective sub-menu element.
}

希望对您有所帮助。

实际上你使用了不正确的 xpath 来定位 pret,summer sale,accessories, bt lawn'16, sale, lookbook, 链接尝试如下:-

List<WebElement> allLinks = driver.findElements(By.cssSelector("a.level0"));
Random random = new Random();
WebElement randomLink = allLinks.get(random.nextInt(allLinks.size()));
randomLink.click();