简体   繁体   中英

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

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

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM