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

落花浮王杯 提交于 2019-12-10 23:08:22

问题


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 :


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/38829086/fetch-all-links-under-in-a-specific-class-selenium-webdriver-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!