Skip to main content
 首页 » 编程设计

python之检查 Web 对象是否在 Selenium 中的其他 Web 对象前面

2025年05月04日34cmt

我有一个 webobject,当我点击它时,我得到:

selenium.common.exceptions.WebDriverException: Message: u'unknown error: Element is not clickable at point (128, 605). Other element would receive the click: ...\n (Session info: chrome=37.0.2062.120)\n (Driver info: chromedriver=2.10.267518,platform=Linux 3.13.0-36-generic x86_64)'

原因是前面还有一个对象,就是关于cookies的消息。那么如何保证点击web对象时前面没有任何东西呢?

示例:

from selenium import webdriver 
 
browser = webdriver.Chrome() 
browser.get("http://cookie-script.com/") 
browser.set_window_size(800, 800) 
 
# Click the Start button that is behind the 'Cookies' popup 
el=browser.find_elements_by_xpath("id('sp-feature')/div[1]/p[2]/a[1]")[0] 
el.click() 

请您参考如下方法:

我似乎通过简单地处理两个特定的异常暂时以一种 hackish 的方式解决了它。

from selenium.common.exceptions import WebDriverException, StaleElementReferenceException 
 
def click_element(el): 
    try: 
        el.click() 
        return True 
    except WebDriverException as exception: 
        print("Could not click on element. Maybe something is in front of it?") 
    except StaleElementReferenceException as exception: 
        print("Reference to element is not valid anymore.") 
    return False 

您可以使用 exception.msg 访问异常消息

这似乎是暂时的。我不确定我是否遗漏了一些案例,但到目前为止它对我有用。好处是,如果点击不成功,您会返回一个 False,这非常有用,因为 Selenium 的 click() 不会返回任何内容。