【问题标题】:How to identify the element with the href attribute using Selenium and C#如何使用 Selenium 和 C# 识别具有 href 属性的元素
【发布时间】:2020-09-14 14:45:34
【问题描述】:

我在选择 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>

我尝试用 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)'

【问题讨论】:

    标签: c# selenium xpath css-selectors webdriverwait


    【解决方案1】:

    您会看到 StaleElementReferenceException 的详细信息有点不确定。但是,该元素是一个Angular 元素,并且在&lt;a&gt; 元素的子&lt;span&gt; 标记内。因此,您必须为所需的ElementToBeClickable() 诱导 WebDriverWait,并且您可以使用以下任一Locator Strategies 作为解决方案:

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

    【讨论】:

    • 我尝试运行,但 xpth 消息出错:测试方法 hw.UnitTest1.TestMethod1 抛出异常:OpenQA.Selenium.WebDriverTimeoutException:20 秒后超时 ---> OpenQA.Selenium.NoSuchElementException : 没有这样的元素: 无法定位元素: {"method":"xpath","selector":"//a[@title='人口和移民局']//span[@class='ng-binding'并且包含(., ' – 人口和移民局')]"} (会话信息: chrome=83.0.4103.61) 堆栈跟踪:
    • @danielshmushmayovich 你试过 CssSelector 了吗?然而,在 contains(., ' – 人口和移民局') 中似乎有额外的
    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2015-12-23
      • 2019-04-21
      • 2022-10-18
      • 1970-01-01
      相关资源
      最近更新 更多