【问题标题】:Selenium finds the element (anchor) but still says element not visible?Selenium 找到了元素(锚),但仍然说元素不可见?
【发布时间】:2020-01-17 08:13:05
【问题描述】:

我有一个“全部清除”按钮,它是一个锚点。 HTML结构是这样的:

<div class="form-row toggle-closed" id="ProductFilters" style="display: block;">
    <div class="form-row__filter">
        <ul class="form-row__filter__bg-display">
            <li class="filter__group__item__small">
                <a id="ProductFiltersFilterText" class="f-right" data-select-all="ProductFilters" href="#">clear all</a>
            </li>
        </ul>
    </div>  
</div>

然后在 Selenium 测试中,我尝试使用以下方法找到 a 标记:

SeleniumHelper.ExpandFilterSection(_webDriver, "#ProductFilters");
var clearAllButton = _webDriver.FindElement(By.CssSelector("div.form-row__filter>ul>li>#ProductFiltersFilterText"));
clearAllButton.Click();

然后我开始调试,在自动 Chrome 窗口中,我可以看到通过执行ExpandFilterSection,过滤器被展开,“全部清除”按钮被暴露,然后一个 bug 说:

OpenQA.Selenium.ElementNotVisibleException: 'element not visible'

我如何在汽车中看到:

好像找到了“全部清除”按钮,为什么说“元素不可见”?按钮的功能是由 JavaScript 触发的。

【问题讨论】:

  • 在点击之前尝试滚动到元素。
  • @supputuri “滚动到元素”是什么意思?
  • var element = driver.FindElement(By.id("ProductFilters")); Actions actions = new Actions(driver); actions.MoveToElement(element); actions.Perform(); 这应该将元素带到可见区域。
  • 为什么不按 id 选择元素?
  • @supputuri 代码给了我错误,你能发布一个答案来解释你的评论吗?

标签: selenium xpath css-selectors webdriverwait linktext


【解决方案1】:

要在文本为 clear all 的元素上 click(),您必须为所需的 ElementToBeClickable() 诱导 WebDriverWait,您可以使用以下任一 @987654321 @:

  • linkText:

    SeleniumHelper.ExpandFilterSection(_webDriver, "#ProductFilters");
    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.LinkText("clear all"))).Click();
    
  • cssSelector:

    SeleniumHelper.ExpandFilterSection(_webDriver, "#ProductFilters");
    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div#ProductFilters>div.form-row__filter>ul.form-row__filter__bg-display>li.filter__group__item__small>a#ProductFiltersFilterText"))).Click();
    
  • xpath:

    SeleniumHelper.ExpandFilterSection(_webDriver, "#ProductFilters");
    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@id='ProductFilters']/div[@class='form-row__filter']/ul[@class='form-row__filter__bg-display']/li[@class='filter__group__item__small']/a[@id='ProductFiltersFilterText']"))).Click();
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2019-10-06
    • 2017-05-07
    • 1970-01-01
    • 2021-08-15
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多