[英]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. 问题是,我正在编写一个测试,要求我单击随机的
item/product
但是如果通过By.tagName("a")
创建所有链接的列表,它将获取页面上的所有链接。 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. 更确切地说,考虑一下该网站 ,现在我想随机从
pret
, summer
sale
, accessories
, bt lawn'16
, sale
, lookbook
或者在单击summer sale
,我想随机单击其下的一种产品。 any idea how to do it? 知道怎么做吗?
here is a snippet of my program : 这是我的程序的片段:
If you want to select all the classes from the site you mentioned, please use below xpath: 如果要从您提到的站点中选择所有类,请在xpath下使用:
List<WebElement> allMenus = driver.findElements(By.xpath(".//a[contains(@class, 'level0')]"));
Then loop through the WebElements
to get to the desired menu item. 然后循环遍历
WebElements
以获得所需的菜单项。 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. 要执行鼠标悬停操作,我们必须使用
Actions
类。 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 :- 实际上,您使用不正确的
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.