danielshmu shmayovich
danielshmu shmayovich

Reputation: 65

How to identify the element with the href attribute using Selenium and C#

I have a problem with select on href

<a id="1 - GovSearch" name="1 - GovSearch" title="Population and Immigration Authority" 
href="https://www.gov.il/en/Departments/population_and_immigration_authority" class="content-title 
first-result" ng-class="{ 'first-result': $first }">
 <!-- ngIf: item.Extension -->
 <span ng-class="item.SubTitle ? 'pipe-after':''" class="ng- 
     binding"> Population and Immigration Authority </span>
                                        <!-- ngIf: item.SubTitle -->
                                    </a>

I tried to make with linktext and getting error:

element.FindElement(By.LinkText("Population and Immigration Authority")).Click();

Getting this error:

OpenQA.Selenium.StaleElementReferenceException: 'stale element reference: element is not attached to the page document (Session info: chrome=83.0.4103.61)'

Upvotes: 2

Views: 600

Answers (2)

user1207289
user1207289

Reputation: 3253

This error is usually caused when element has changed or removed because of something that user has tried to do. You can try catching exception and then click again

try {
    element.FindElement(By.LinkText("Population and Immigration Authority")).Click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
   element.FindElement(By.LinkText("Population and Immigration Authority")).Click();
}

Webdriver internally uses getElementAt method and a unique id called UUID to locate elements. Anytime this UUID changes for an element because of any reason and the call that user is making refers to old UUID, getElementAt method throws exception. You can also see exception referring to fxdriver.cache.getElementAt method. You can find official explanation of this error here

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193088

A bit unconclusive from the details why you would see a StaleElementReferenceException. However, the element is an Angular element and within the child <span> tag of the <a> element. So you have to induce WebDriverWait for the desired ElementToBeClickable() and you can use either of the following Locator Strategies as solutions:

  • CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("a[id$='GovSearch'][name$='GovSearch'][title='Population and Immigration Authority'] span.ng-binding"))).Click();
    
  • XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//a[@title='Population and Immigration Authority']//span[@class='ng-binding' and contains(., 'Population and Immigration Authority')]"))).Click();
    

Upvotes: 3

Related Questions