【问题标题】:Selenium WebDriver cannot click element even though it seems to be visibleSelenium WebDriver 无法单击元素,即使它似乎是可见的
【发布时间】:2018-12-08 13:53:12
【问题描述】:

使用 Python 2,使用 Firefox 的 Selenium,在此 page 上,我正在尝试让驱动程序单击以下按钮(放大镜):

<button id="search-btn" type="button" class="header__user-menu-item header__search-btn">
          <span class="sr-only">Search</span>
          <img src="/sites/default/themes/custom/smp_bootstrap/images/search.svg" class="header__user-menu-icon fa fa-search fa-fw" alt="Search">
        </button>

我将以下代码用于元素的 XPath,x = '//*[@id="search-btn"]'

x = '//*[@id="search-btn"]'

try:
    element = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, x)))
except:
    print "Element not clickable"
else:
    found_element = driver.find_element_by_xpath(x)
    try:
        found_element.click()
    except:
        raise

Selenium 的常见异常 EC.element_to_be_clickable 不识别元素,visibility_of_element_locatedpresence_of_element_located 也不识别。

然而,奇怪的是,在某些情况下,驱动程序实际上能够识别元素,然后执行driver.find_element_by_xpath(x),这似乎找到了 XPath 和 .click() 元素。那时一切正常。有那么一秒钟,我认为脚本在页面加载之前快速执行操作,但 5 秒 WebDriverWait 足以加载页面,并且在此之前我还有一个额外的页面加载睡眠。

该元素似乎不在 IFrame 中。我已经通过了“接受条件”-按钮等。

我正在运行最新版本的 Firefox (61.0)、Selenium (3.13) 和 Geckodriver (0.21.0)。

这可能是什么问题?

【问题讨论】:

  • 你用的是哪个驱动?
  • @cle-b 火狐。抱歉,将其添加到问题中。
  • 尝试使用 Chrome,在 chrome 中可以使用 xpath 和 id

标签: python python-2.7 selenium selenium-webdriver


【解决方案1】:

如果我用By.ID 得到元素而不是By.XPATH 这有效,也许你给错了xpath

如果使用xpath,这也可以x = '//*[@id="search-btn"]'

id = 'search-btn'
element = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.ID, id)))
element.click() 

【讨论】:

    【解决方案2】:

    您可以按如下方式定位&lt;img&gt; 标记,而不是定位&lt;button&gt; 元素:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//img[@class='header__user-menu-icon fa fa-search fa-fw' and @alt='Search']"))).click()
    

    【讨论】:

    • 谢谢,你是对的。然而,我之前确实尝试过,不幸的是它与这个问题无关。
    【解决方案3】:

    使用 Firefox 作为驱动,我可以通过执行 JavaScript 来点击元素:

    driver.execute_script("window.document.getElementById('search-btn').click()")
    

    请注意,以上是非常规措施,不需要。其他答案都是正确的,并且是通常的做法。

    问题在于 Selenium 驱动程序无法识别 XPath 元素,因为当前版本的 geckodriver (0.21.0) 与 Selenium (3.13.0) 结合使用时存在错误,请参阅:Broken pipe error selenium webdriver, when there is a gap between commands?

    为了避免这个问题,我降级到 geckodriver 0.20.1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 2015-09-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多