selenium:等待元素可点击不起作用

时间:2017-08-12 18:52:37

标签: python selenium selenium-webdriver

我正在尝试使用expected_conditions.element_to_be_clickable但它似乎不起作用。在大约30%的运行中,我仍然看到“元素......在点上无法点击”错误。

以下是完整的错误消息:

  

selenium.common.exceptions.WebDriverException:消息:未知   错误:元素...在点(621,337)处无法点击。其他   元素会收到点击:...         (会话信息:chrome = 60.0.3112.90)         (驱动信息:chromedriver = 2.26.436421(6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6),platform = Mac OS X 10.12.6   x86_64的)

这是我正在使用的代码:

def wait_for_element_to_be_clickable(selector, timeout=10):
  global driver
  wd_wait = WebDriverWait(driver, timeout)

  wd_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, selector)),
    'waiting for element to be clickable ' + selector)
  print ('WAITING')
  return driver.find_element_by_css_selector(selector)

更新

所以现在这真的很奇怪。即使我添加了几个固定的等待时间,它仍会偶尔抛出错误消息。这是调用的代码:

  sleep(5)
  elem = utils.wait_for_element_to_be_clickable('button.ant-btn-primary')
  sleep(5)
  elem.click()

2 个答案:

答案 0 :(得分:2)

结束创建我自己的自定义函数来处理异常并执行重试:

""" custom clickable wait function that relies on exceptions. """
def custom_wait_clickable_and_click(selector, attempts=5):
  count = 0
  while count < attempts:
    try:
      wait(1)
      # This will throw an exception if it times out, which is what we want.
      # We only want to start trying to click it once we've confirmed that
      # selenium thinks it's visible and clickable.
      elem = wait_for_element_to_be_clickable(selector)
      elem.click()
      return elem

    except WebDriverException as e:
      if ('is not clickable at point' in str(e)):
        print('Retrying clicking on button.')
        count = count + 1
      else:
        raise e

  raise TimeoutException('custom_wait_clickable timed out')

答案 1 :(得分:1)

问题在错误消息中说明。

  

元素...在点(621,337)处无法点击。其他元素会收到点击:...

问题在于某些元素,即您从错误消息中删除的详细信息,在您尝试单击的元素之上。在许多情况下,这是一些对话框或其他一些UI元素。如何处理这取决于具体情况。如果是打开的对话框,请将其关闭。如果它是一个关闭的对话框但代码运行速度很快,请等待对话框的某些UI元素不可见(对话框已关闭且不再可见)然后尝试单击。通常,它只是读取阻塞元素的HTML,在DOM中找到它,并弄清楚如何等待它消失等等。

相关问题