I want to test if the value in my href attributes in my a tags are relative paths using Selenium.
This is my HTML:
<a href="/about/somepage/">my page</a>
I use selenium to select the a tag:
string hrefValue = _chromeDriver.FindElement(By.TagName("a")).GetAttribute("href");
This will return "http://mydomain/about/somepage/" even if the part "http://mydomain" is not in the HTML.
If I use GetAttribute("pathname")
it will give what I want, however the GetAttribute("pathname")
will only give the value "/about/somepage/"
EVEN if the HTML looks like this:
<a href="http://myDomain/about/somepage/">my page</a>
So, how can I test if the actual value of the href
attribute is relative or not to my website?
The easiest way to do this is to look for the A tag but also examine its href attribute and see if it starts with "http".
Console.WriteLine(driver.FindElements(By.CssSelector(a[href^='http'])).Any());
If this prints False then it's relative.
Java version:
retrieve outerHTML
of the element (link) and check whether it contains http://
in it.
WebElement link = driver.findElement(By.linkText("my page"));
String href = link.getAttribute("href");
String outerHtml = link.getAttribute("outerHTML");
System.out.println("href " + href);
System.out.println("outerHtml " + outerHtml);
if(outerHtml.contains("href=\"http://")){
System.out.println(href + " is absolute path");
}
else{
System.out.println(href + " is relative path");
}
First, get all the links whose href start with http. Since, links may be both absolute or relative and you don't whether your desired one is starting with http so, an extra checking is necessary if list is greater than 1. Here is the code snippet-
List<WebElement> links = driver.findElements(By.cssSelector("a[href^='http']"));
if (links.size() == 0) {
System.out.println("relative");
}else {
boolean isAbsolute = false;
for (WebElement link: links ) {
if(link.getText().equals("Visit 2.com!")){
isAbsolute = true;
break;
}
}
if (isAbsolute) {
System.out.println("absolute");
}else {
System.out.println("relative");
}
}
Try this it should give you everything inside <a>
and then you can check it :
string hrefValue = _chromeDriver.FindElement(By.TagName("a")).getAttribute("innerHTML")
Edit:
try with outerHTML
instead. It should give the whole thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With