selenium 如何验证链接

hwazgwia  于 2022-12-18  发布在  其他
关注(0)|答案(5)|浏览(210)

How to verify whether links are present or not?
eg. I have 10 links in a page, I want to verify the particular link
Is it possible? I am using selenium with Java.
Does i can write inside the selenium code
eg

selenium.click("searchimage-size");    
selenium.waitForPopUp("dataitem", "3000");    
selenium.selectWindow("name=dataitem");    

foreach(var link in getMyLinkTextsToTest())    
{
    var elementToTest = driver.findElement(By.linkText(link));    
    Assert.IsNotNull(elementToTest);    
}
a1o7rhls

a1o7rhls1#

What you can do is find all links on the page like this:

var anchorTags driver.findElement(By.TagName("a"));

and then iterate through the anchorTags collection to make you you've got what you're looking for.
Or if you have a list of the link texts you can do something like this:

foreach(var link in getMyLinkTextsToTest())
{
var elementToTest = driver.findElement(By.linkText(link));
Assert.IsNotNull(elementToTest);
}

This code is all untested and right off the top of my head so you might need to do some slight modification but it should be close to usable.

yh2wf1be

yh2wf1be2#

如果您使用的是Selenium 1.x,则可以使用以下代码。

String xpath = "//<xpath till your anchor tag>a/@herf";
        String href = selenium.getAttribute(xpath);
        String expectedLink = "your link";
        assertEquals(href,expectedLink);
bmp9r5qi

bmp9r5qi3#

我希望这能帮助你...

List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement we : links) {
   if("Specific link text".equals(we.getText("Specific link text"))) {
      we.click();
   }
}

字符串
我把所有的链接都放到List变量“links”中并迭代它。然后检查条件,我们在链接中查找的特定文本是否出现在列表中。如果它发现了,它会点击它

jvidinwx

jvidinwx4#

If you're looking to verify each specific <a href="..."></a> for the content of href, you can use javascript to return the outerHTML for a specific Webelement which you can identify however you like; in the example below I use By.cssSelector:

WebElement Element = driver.findElement(By.cssSelector("..."));
String sourceContents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].outerHTML;", element); 
assertEquals(sourceContents, "<a href=\"...YOUR LINK HERE..." target=\"_blank\">Learn More</a>");

If you want to make it a tad more elegant you can shave the undesired elements off of the string, but this is the general case as of Selenium-java: 2.53.1 / Selenium-api: 2.47.1 as I can observe.

im9ewurl

im9ewurl5#

最好的方法是使用getText()方法

List<WebElement> allLinks = driver.findElements(By.tagName("a"));
 for(WebElement specificlink : allLinks ) {
   if(specificlink.getText().equals("link Text"){
    //SOPL("Link found");
    break;
 }
}

相关问题