如何使用 Selenium 和 C# 识别具有 href 属性的元素

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

我对 href

上的 select 有疑问
<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>

我尝试使用 linktext 进行制作,但出现错误:

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

出现此错误:

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

关于为什么您会看到 StaleElementReferenceException 的细节有点不确定。然而,该元素是一个 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 作为解决方案:

  • 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();
    

此错误通常是由于用户尝试执行某些操作而更改或删除元素时引起的。您可以尝试捕获异常然后再次单击

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 在内部使用 getElementAt 方法和一个名为 UUID 的唯一 ID 来定位元素。任何时候这个 UUID 由于任何原因对元素发生更改并且用户正在进行的调用引用旧的 UUIDgetElementAt 方法抛出异常。您还可以看到引用 fxdriver.cache.getElementAt 方法的异常。你可以找到这个错误的官方解释 here