5

I am using selenium to get href attribute, lLinks are my web element that has a "href" attribute.

String url = lLinks.getAttrbute("href");

If the href of my 'a' tag is a relative path like <a href='/home'>Home</a> , the url will return http://www.domain.com/home.

How do I get the url to just equal to the exact text of the href attribute?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Ming Huang
  • 1,310
  • 3
  • 16
  • 25

2 Answers2

6

I think you cannot get that "href". Selenium only provides a full path or a relative path. See code below:

String href = linx.getAttribute("href");
System.out.println("Text is" + href);
String pathName = linx.getAttribute("pathname");
System.out.println("Text is" + pathName);
// Results
// Text is http://www.amazon.com/gp/yourstore/home/ref=nav_cs_ys/180-1519742-0316250
// Text is /gp/yourstore/home/ref=nav_cs_ys/180-1519742-0316250
Buaban
  • 5,029
  • 1
  • 17
  • 33
  • The problem with this is that the pathname will give /gp/yourstore/etc even if the href actually contains http://www.amazon.com/. So if you are testing to se if the href is set to relative, this will not work – andreasnico Nov 30 '16 at 13:15
  • @andreasnico I don't get your point. Can you rephrase your comment? – Buaban Nov 30 '16 at 13:19
  • @andreasnico I get your point now. As I mentioned, you cannot get the property "href". It allows you to get full path and relative path, not the property. – Buaban Nov 30 '16 at 13:28
5

You can obtain href attribute by reading the whole element:

lLinks.getAttribute("outerHTML")

Which gives you e.g.:

<a id="button-id" href="#">Click me!</a>

Then you can use pattern matching to get the href attribute.

Jack Miller
  • 6,843
  • 3
  • 48
  • 66