4

I am looking for a way to pull the html or text content of a so I could work with it for a method which validates links amongst text of messages displays on a webpage. I am using selenium and java.

<div>
    "This link"
    <a href="http://www.google.com">http://www.google.com</a>
    "exists." 
</div>

I have been researching ways to pull the html of the link from a single message and most of what I have encountered allows you to pull the text of the 'href' attribute or the link text. It may not be possible. Preferably, I would like to pull all the content from the div.

I have tried something similar to this below but it returns 'http://www.google.com'.

WebElement e = driver.findElements(By.tagName("a"));
String content = e.getAttribute("innerHTML");  

I have also tried using xpaths using contains() and text(). Both return the text of link but not anything else.

Any ideas what I could try?

1 Answer 1

2

Try using this:

WebElement e = driver.findElements(By.xPath("//a/.."));

It will select the parent element, the div in this case, of every a. If you want to add a predicate (that is, a condition) for which to filter, you can do this:

WebElement e = driver.findElements(By.xPath("//a[contains(@href, 'http:')]/.."));

I chose // as start, which searches the whole document. If you want to search only a part, change that to an XPath expression that only selects that part.

5
  • (not sure it is By.xPath() or By.xpath() or By.XPATH(), as apparently, it may depend on the host language of Selenium that you have chosen).
    – Abel
    Commented Sep 24, 2015 at 22:04
  • I am using java. The xpath("//a/..") worked like a charm. It was able to pull the html link for me. Now I am trying to figure out how to pull the text around the link at the same too. Any suggestions?
    – MikeG
    Commented Sep 28, 2015 at 14:43
  • @user1397534, that depens on how that is structured and what you mean by "around the link": before and after the link, the linktext, the title-text, etc. You can use XPath to get siblings (following-sibling and preceding-sibling), to get the parent, the parent's siblings etc. If you are unsure what to do, try it first on xpathtester.com or with FirePath or similar tools. If you can't work it out, post a new question. and if this answer helped you, feel free to upvote and/or accept it ;).
    – Abel
    Commented Sep 28, 2015 at 14:55
  • @user1397534, from your question, you can get the text nodes "this link" and "exists" by using //a/parent::div/text(), or something similar.
    – Abel
    Commented Sep 28, 2015 at 14:57
  • Thank you for the quick replies. I got it working. Thanks.
    – MikeG
    Commented Sep 28, 2015 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.