Reputation: 407
I have some html code with href links. Some of them are as follows:
<a href="#">
while others are like
<a href = "http://.....'>.
In other words for an xpath I can't use //a[contains(@href,'#')]
nor //a[contains(@href,'http')]
because they are mutually exclusive and each would work only for certain different href values. There is not a universal string I can search for.
Now, theoretically, href should not be blank so if I could use something like //a[href not blank]
that would be good. Or even //a[has href attribute]
.
Anyway to do that?
Upvotes: 2
Views: 1913
Reputation: 25746
I would use a simple CSS Selector that looks for an A
tag that has an href
attribute.
List<WebElement> elements = driver.findElements(By.cssSelector("a[href]"));
Upvotes: 0
Reputation: 11971
You could also check for specific instances of a
tags using the XPath or operator:
driver.findElements(By.xpath("//a[@href='#' or starts-with(@href, 'http://')]")
This returns all anchor tags that have an href
attribute equal to #
or an href
attribute that starts with http://
.
This solution isn't as easy as the one from @alecxe, but it might give you more flexibility with your selections moving forwards. It also gives you the option to 'filter out' unwanted anchor tags. For example, this solution wouldn't return anchor tags with an href
attribute that is a relative path eg href="path/to/another/webpage.html"
.
Upvotes: 0
Reputation: 474171
If you want to check for a
links to have the href
attribute:
driver.findElements(By.xpath("//a[@href]"));
Upvotes: 2