2017-08-12 107 views
0

我试图使用expected_conditions.element_to_be_clickable,但它似乎没有工作。在大约30%的运行中,我仍然看到“元素...在点上不可点击”的错误。selenium:等待元素可点击不起作用

以下是完整的错误消息:

selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (621, 337). Other element would receive the click: ... (Session info: chrome=60.0.3112.90) (Driver info: 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() 

回答

0

问题在错误消息中说明。

Element ... is not clickable at point (621, 337). Other element would receive the click: ...

问题是某些元素(您从错误消息中删除的细节)位于您尝试点击的元素的顶部。在很多情况下,这是一些对话或其他一些UI元素。如何处理这取决于情况。如果它是一个打开的对话框,关闭它。如果它是一个关闭的对话框,但代码运行速度很快,请等待对话框的某个UI元素不可见(对话框关闭,不再可见),然后尝试点击。通常它只是读取阻塞的元素的HTML,在DOM中找到它,并找出如何等待它消失等。

+1

有人会认为该函数在进行isClickable测定时会考虑到这一点。我最终创建了自己的函数来捕获异常并执行重试。 – opike

0

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

""" 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') 
相关问题