Common HTML Find Expressions

I would like to click on a hyperlink based on its text value. I prefer to do this in code and not by editing an existing element's Find Settings.

Solution

Let's use wikipedia.org as an example. First we'll find and click the top bold English link.

wikipedia

Here's the HTML code for that link:

<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia">
<strong>English</strong>
<br>
<em>The Free Encyclopedia</em>
<br>
<small>3 907 000+ articles</small>
</a>

The anchor element has no direct TextContent, so we'll need to locate by a partial match on InnerText:

HtmlAnchor a = Find.ByExpression<HtmlAnchor>("InnerText=~English", "tagname=a");
Assert.IsNotNull(a);
a.Click();
Dim a As HtmlAnchor = Find.ByExpression(Of HtmlAnchor)("InnerText=~English", "tagname=a")
Assert.IsNotNull(a)
a.Click()

If we locate by an exact match on TextContent, the bottom English link will found.

english link

Here's the HTML code for that link:

<a href="//en.wikipedia.org/" lang="en">English</a>

Here's how to locate and click that link:

HtmlAnchor a = Find.ByExpression<HtmlAnchor>("TextContent=English", "tagname=a");
Assert.IsNotNull(a);
a.Click();
Dim a As HtmlAnchor = Find.ByExpression(Of HtmlAnchor)("TextContent=English", "tagname=a")
Assert.IsNotNull(a)
a.Click()

The following attributes apply to both links, however Test Studio returns the first HtmlAnchor that matches. In this case, that's the top bold English link.

HtmlAnchor a = Find.ByExpression<HtmlAnchor>("tagname=a", "href=//en.wikipedia.org/");
Dim a As HtmlAnchor = Find.ByExpression(Of HtmlAnchor)("tagname=a", "href=//en.wikipedia.org/")

You can find it by xpath:

HtmlAnchor a = Find.ByXPath<HtmlAnchor>("//*[@id=\"www-wikipedia-org\"]/div[5]/div/a[2]");
Dim a As HtmlAnchor = Find.ByXPath(Of HtmlAnchor)("//*[@id=""www-wikipedia-org""]/div[5]/div/a[2]")

You can also data drive the find expression:

HtmlAnchor a = Find.ByExpression<HtmlAnchor>("tagname=a", "textcontent=" + Data["Col1"].ToString());
Dim a As HtmlAnchor = Find.ByExpression(Of HtmlAnchor)("tagname=a", "textcontent=" + Data("Col1").ToString())