Home > Back-end >  How to click <a> anchor tag link only knowing its span with Selenium C#
How to click <a> anchor tag link only knowing its span with Selenium C#

Time:06-30

On a web page there is this anchor that I want to click using Selenium:

<a onclick='ejecutaOpcion(this, '/srDocumentoAdmRecepcion.do?accion=goInicioGet&estadoDoc=01&coDep=10016','POST');' class='menu_lista' href='#'>
   <span>Recepción de Documentos</span>
</a>

There is no Id or Name for that anchor and class "menu_lista" is used for other anchors in same web page.

I've tried:

var recepcionLink = myWebDriver.FindElement(By.XPath("//a[@class='menu_lista']/span[text()='Recepción de Documentos']"));
recepcionLink.Click();

However, I got exception:

OpenQA.Selenium.ElementNotInteractableException: 'element not interactable (Session info: chrome=103.0.5060.53)'

It looks like I'm getting the span element but not the anchor element.

CodePudding user response:

You can try using linktext.

driver.findelement(By.xpath("//span[text()='Recepción de Documentos']/../a).Click();

CodePudding user response:

Try using relative locators (new in Selenium 4)

WebDriver.FindElement(RelativeBy
  .WithLocator(By.CssSelector("a.menu_lista span"))
  .Near(By.TagName("a")));

Docs https://www.selenium.dev/documentation/webdriver/elements/locators/#available-relative-locators

  • Related