fetch all links under/in a specific class-selenium

2019-07-17 18:27发布

Is there a way to fetch all the links under a specific class?

The thing is, iI am writing a test that requires me to click on a random item/product but if a create a list of all the links through By.tagName("a"), It'll fetch ALL the links on the page. To be more exact, consider this website, Now I want to randomly choose from pret,summer sale,accessories, bt lawn'16, sale, lookbook or after clicking on summer sale, I want to randomly click on one of the products under it. any idea how to do it?

here is a snippet of my program :

https

2条回答
相关推荐>>
2楼-- · 2019-07-17 19:00

Actually you are using incorrect xpath to locating pret,summer sale,accessories, bt lawn'16, sale, lookbook, links try as below :-

List<WebElement> allLinks = driver.findElements(By.cssSelector("a.level0"));
Random random = new Random();
WebElement randomLink = allLinks.get(random.nextInt(allLinks.size()));
randomLink.click();
查看更多
男人必须洒脱
3楼-- · 2019-07-17 19:04

If you want to select all the classes from the site you mentioned, please use below xpath:

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

Then loop through the WebElements to get to the desired menu item. Also, it is observed that the sub-menu items are getting displayed after the mouse is hovered on a particular item. To perform the mouse hover operation we have to use Actions class. Please find the below code for your reference.

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.
}

Hope this helps.

查看更多
登录 后发表回答