如何使用selenium-java单击href链接

问题描述 投票:0回答:2

我正在使用selenium-java来自动化一些测试(这是自学的)。我被困在单击超链接中,但是这个href非常特别,因为像这样:

<a tabindex="-1" href="../../myWebPage.html"><span>My Web Page</span></a>

我的Java代码是:

1.-driver.findElement(By.xpath("//a[@href='../../myWebPage.html']")).click();2.- driver.findElement(By.xpath("//a[@href='https://RealHost/pag1/myWebPage.html']")).click();

我使用的第二个选项是真正的链接,但是它们都不起作用。

您能帮我吗?

P.S:我也使用了选项driver.findElement(By.LinkText("https://RealHost/pag1/myWebPage.html")).click();,但没有成功。

谢谢你们!

java selenium xpath automation href
2个回答
0
投票

尝试使用任何一个xpath。

driver.findElement(By.xpath("//a[contains(@href,'/myWebPage.html')]//span[text()='My Web Page']")).click();

OR

driver.findElement(By.xpath("//a[.//span[text()='My Web Page']]")).click();

或CSS选择器

driver.findElement(By.cssSelector("a[href*='/myWebPage.html']>span']")).click();

0
投票

您应该能够通过首先查看DOM并为其找到xpath来找到其父元素,从而找到链接元素。然后使用该父元素来查找带有“ a”标签的元素

WebElement parent = findElement(By.xpath("/*path to parent element here*/"));
parent.findElement(By.tagName("a")).click();

请注意,如果是这种情况,则父元素可能具有tagName的多个子元素,请使用findElements()获取该父元素所有超链接的集合。然后在集合中搜索所需的集合。

WebElement parent = findElements(By.xpath("/*path to parent element here*/"));
List<WebElement> elements = parent.findElements(By.tagName("a")).click();
//search the list for the correct link

您可以尝试的另一件事是通过linkText查找元素。

findElement(By.linkText("/*The hyperlinks text*/")).click();

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.