BegJavaPy
BegJavaPy

Reputation: 95

How can i extract the email id from the href link using selenium

I have the following HTML code from which I need to extract the email ID.

<div class="Serial">
<p> … </p>
<p>
<span>
<a href="mailto:[email protected]">
    Mr. XYZ
</a>
</span>
</p>
<p> … </p>
<p> … </p>

The above email Id's are generated from a series of random numbers. I need to iterate it many times and every time I try to get the mail id, its failing.

I am using for loop to iterate for n times and trying with the following code :

WebElement link = driver.findElement(By.linkText("Mr.XYZ").getAttribute("href");
Assert.assertTrue(link.contains("mailto : ....")

It works fine for the first iteration and fails later. How can I get the mail Id's every time I run the code?

Upvotes: 1

Views: 1860

Answers (2)

ddavison
ddavison

Reputation: 29052

I still prefer @Arran's answer, but I think the error you were seeing was because you were missing 1 measly character.

By.linkText("Mr.XYZ")

should have been

By.linkText("Mr. XYZ") // note the space.

Upvotes: 0

Arran
Arran

Reputation: 25076

You just need to think about it in a different way, specifically think about how it sits within the whole document. You are using .linkText so you are currently bound to what text is being shown.

You can change this by using a CSS selector.

In your example, we can assume that the anchor is only link within that overlying div with a class Serial. That way, you could have a CSS selector like so:

div.Serial > a

Meaning, it doesn't matter what text is has inside it.

You could go a little further and say, well, there are other links in there too so we will ensure we only get ones that have mailto: in them:

div.Serial > a[href^='mailto:']

Upvotes: 3

Related Questions