【问题标题】:Unable to locate element using Selenium Chromedriver when it's there in C#无法使用 Selenium Chromedriver 在 C# 中定位元素
【发布时间】:2020-11-07 16:36:32
【问题描述】:

我试图让我的程序点击一个按钮,但我收到错误。

我的代码:

driver.FindElementById("couponsinc-gallery-selectall").Click();

错误:

An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll
no such element: Unable to locate element: {"method":"css selector","selector":"#\couponsinc\-gallery\-selectall"}

这是页面上按钮的代码:

<div class="selectall">
            <input type="checkbox" class="selectall-chk" id="couponsinc-gallery-selectall">
            <label for="couponsinc-gallery-selectall">Clip All</label>
        </div>

我也尝试过使用FindElementByClassName,但没有任何效果。我做错了什么?

【问题讨论】:

    标签: c# selenium xpath css-selectors webdriverwait


    【解决方案1】:

    的文本为 Clip All&lt;iframe&gt;,因此您必须:

    • 诱导WebDriverWait 使所需的框架可用并切换到它

    • 诱导WebDriverWait 使所需的元素可点击

    • 您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR

      ((IJavaScriptExecutor)driver).ExecuteScript("return scrollBy(0, 800);");
      new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.CssSelector("iframe[title='Coupons']"));
      new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.selectall-chk#couponsinc-gallery-selectall"))).Click();
      
    • 使用XPATH

      ((IJavaScriptExecutor)driver).ExecuteScript("return scrollBy(0, 800);");
      new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.XPath("//iframe[@title='Coupons']"));
      new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@class='selectall-chk' and @id='couponsinc-gallery-selectall']"))).Click();
      
    • 浏览器快照:


    参考

    您可以在以下位置找到一些相关讨论:

    【讨论】:

    • 我试过这个并且得到了这个错误:OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 20 seconds' with the same internal exception: NoSuchElementException: no such element: Unable to locate element, here是网站:keyfood.com/store/keyFood/en/printable-coupons,你可以自己测试一下,就是靠近页面底部的“Clip All”按钮。
    • @africohal 查看更新的答案并告诉我状态。
    • 这次我得到了这个异常:OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 20 seconds' 其次是这个内部异常: InvalidSelectorException: invalid selector: 指定了一个无效或非法的选择器,发生在这个line: new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("//input.selectall-chk#couponsinc-gallery-selectall"))).Click();跨度>
    • @africohal 我的错,这是一个错字,已修复,请现在检查两个定位器并让我知道状态。
    • 太棒了!该解决方案似乎有效,我已将其标记为解决方案,但我仍然不明白为什么我的简单代码不起作用,因为它肯定适用于不同网站上的不同按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2016-12-10
    • 2018-11-29
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多