Xpath to an anchor returning error: unable to locate element



  • I am new to automated testing. I am using C#, Selenium and Chrome 99 with the correct driver. I am trying to get to an anchor tag on the page.

    Here is my code that is not working,

    driver.Url = "abc.com"; //cant display the real one
    driver.FindElement(By.XPath("//a[@href='ubEntryQueue.aspx']")).Click();
    

    The error I am getting:

    OpenQA.Selenium.NoSuchElementException
      HResult=0x80131500
      Message=no such element: Unable to locate element: {"method":"xpath","selector":"/a[@href='ubEntryQueue.aspx']"}
      (Session info: chrome=99.0.4844.74)
      Source=WebDriver
      StackTrace:
       at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse)
       at OpenQA.Selenium.WebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
       at OpenQA.Selenium.WebDriver.FindElement(String mechanism, String value)
       at OpenQA.Selenium.By.b__11_0(ISearchContext context)
       at OpenQA.Selenium.By.FindElement(ISearchContext context)
       at OpenQA.Selenium.WebDriver.FindElement(By by)
       at CLQTesting.WQ.ValidateWQDisplays() in C:\QA\CLQTesting\WQ.cs:line 30
    

    This was my last attempt

    Here is what I am trying to get to enter image description here



  • The problem is that the parent div (and possibly other parent elements as well) has a style attribute of display:none which prevents any child elements from displaying.

    There are several ways to get around this problem.

    1. Program the actions needed to make the target element display. This may or may not be feasible depending on the way the site works - the HTML snippet shown in the question suggests that a lot of JavaScript is used to handle changing visibility and expanding elements.
    2. Use the WebDriver JavaScriptExecutor class ExecuteScript method to edit the style directly. To do this, you will need to get a reference to a parent of the element with display:none, then use ExecuteScript to traverse the DOM and delete the display:none style tag. From there you can proceed as normal.
    3. Use JavaScriptExecutor to click the link directly. This is probably the simplest method.

    You can find a decent guide to using JavaScriptExecutor https://www.lambdatest.com/blog/how-to-use-javascriptexecutor-in-selenium-webdriver/ . (I found the link with a quick Google search. No affiliation)




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2