Hi

driver.FindElement with a href seleium with c#

 <a> tag (<a href="some_url">Link</a>) using driver.FindElement in Selenium C#, you can use different locators depending on your needs.

If you want to locate an anchor (<a>) element using the href attribute, use XPath:

IWebElement link = driver.FindElement(By.XPath("//a[@href='https://example.com']"));

link.Click();

If the href value contains dynamic parameters or is long, use contains():

IWebElement link = driver.FindElement(By.XPath("//a[contains(@href, 'example.com/page')]"));
link.Click();

Find <a> Tag by Text

If you want to click an anchor by its visible text:


IWebElement link = driver.FindElement(By.LinkText("Click Here")); link.Click();

🔹 This works only if the text inside <a> is exactly "Click Here".

If the text may have extra words, use:


IWebElement link = driver.FindElement(By.PartialLinkText("Click")); link.Click();

🔹 This matches any <a> tag that contains "Click" in its text.


Find <a> Using CSS Selector

If you prefer CSS selectors:


IWebElement link = driver.FindElement(By.CssSelector("a[href='https://example.com']")); link.Click();

🔹 CSS selector does not support contains(), so it only works for exact matches.


Find Multiple <a> Links

If there are multiple <a> tags and you want all of them:


IList<IWebElement> links = driver.FindElements(By.XPath("//a")); foreach (IWebElement link in links) { Console.WriteLine(link.Text + " -> " + link.GetAttribute("href")); }

🔹 This prints all links on the page with their text and URL.


🔥 Handling Click Issues

If .Click() is not working, try:


IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript("arguments[0].click();", link);

or scroll before clicking:


js.ExecuteScript("arguments[0].scrollIntoView(true);", link); Thread.Sleep(500); link.Click();

🛠 Debugging Tip

To verify if the element is found, print its details before clicking:


Console.WriteLine(link.GetAttribute("outerHTML"));


  • XPathBy.XPath("//a[@href='URL']") (best for precise matches)

  • Partial hrefBy.XPath("//a[contains(@href, 'text')]")

  • Text matchBy.LinkText("Exact Text") or By.PartialLinkText("Partial")

  • CSS SelectorBy.CssSelector("a[href='URL']")

  • Handle click issues → Use JavaScript or scroll into view


Previous
Next Post »