Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exact text of href attribute of tag a?

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?

like image 995
Ming Huang Avatar asked Feb 18 '16 23:02

Ming Huang


People also ask

How do you get a href value of a tag in BeautifulSoup?

To get href with Python BeautifulSoup, we can use the find_all method. to create soup object with BeautifulSoup class called with the html string. Then we find the a elements with the href attribute returned by calling find_all with 'a' and href set to True .

What is the href attribute of a tag?

The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!

Is href a tag or an attribute?

The HREF is an attribute of the anchor tag, which is also used to identify sections within a document. The HREF contains two components: the URL, which is the actual link, and the clickable text that appears on the page, called the "anchor text."


2 Answers

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
like image 88
Buaban Avatar answered Nov 10 '22 20:11

Buaban


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.

like image 38
Jack Miller Avatar answered Nov 10 '22 18:11

Jack Miller