OpenQA.Selenium.NoSuchElementException : no such element: Unable to locate element

108 Views Asked by At

I have a webpage that i am trying to automate with selenium using this practice website https://practicetestautomation.com/practice-test-login/, I have wait conditions in my script so im not sure why this is happening. Selenium is not able to locate the link an throwing this exception:

OpenQA.Selenium.NoSuchElementException : no such element: Unable to locate element: {"method":"link text","selector":"Practice"} (Session info: chrome=119.0.6045.106); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

I am trying to locate the 'Practice' Url on the page, and this is the code for the web page where the url exists: enter image description here

<nav class="menu"><ul id="menu-primary-items" class="menu-primary-items"><li id="menu-item-43" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home menu-item-43"><a href="https://practicetestautomation.com/">Home</a></li>
<li id="menu-item-20" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-20"><a href="https://practicetestautomation.com/practice/">Practice</a></li>
<li id="menu-item-21" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-21"><a href="https://practicetestautomation.com/courses/">Courses</a></li>
<li id="menu-item-19" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-19"><a href="https://practicetestautomation.com/blog/">Blog</a></li>
<li id="menu-item-18" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-18"><a href="https://practicetestautomation.com/contact/">Contact</a></li>
</ul></nav>

this is the code in Selenium that says i have a problem with,:

IWebElement link = driver.FindElement(By.LinkText("Practice"));
String hrefAttr = link.GetAttribute("href");
3

There are 3 best solutions below

0
Shawn On

When you can't locate the element using one locator strategy(in your case LinkText), you can always try with other locator strategies(say XPATH). Try using the following XPath expression - //li[@id='menu-item-20']//a

Change your code as below:

IWebElement link = driver.FindElement(By.XPath("//li[@id='menu-item-20']//a"));
String hrefAttr = link.GetAttribute("href");
0
Gulzhas Mailybayeva On

As mentioned above, try to change linkTest to xpath:

//a[text()='Practice']

also you can add implicitlyWait

0
Michał Cichoń On

In this case you have dynamically li class name, so you should use XPath for filtering based on text like

string nameForFiltering = "Practice";
var element = driver.FindElement(By.XPath($"//nav[@class='menu']/ul/li/a[text()='{nameForFiltering }']"));