Skip to main content
 首页 » 编程设计

python之无法使用 Selenium 在 Python 中的关闭窗口中找到元素

2025年02月15日7落叶无声

def check_text(browser, sitename): 
 
    browser.get(sitename) 
 
    try: 
        text = browser.find_element_by_class_name("text_content").text 
 
        if "foo" in text: 
            print("ok") 
 
        else: 
            print("not ok") 
 
    except NoSuchElementException: 
        print("no such elem") 
 
 
def check_internet_explorer(): 
 
    sitename="*foo site*" 
    caps = DesiredCapabilities.INTERNETEXPLORER 
    caps['ignoreProtectedModeSettings'] = True 
    ie = webdriver.Ie(capabilities=caps) 
    check_text(ie, sitename) 

此代码在 Windows 10 上运行良好。当我尝试在 Windows 7 上运行它时,网页加载但出现此错误:“无法在关闭的窗口上找到元素” 我在网上查找了这个错误,它与 Internet Explorer 保护模式有关。我尝试添加“忽略保护模式设置”功能,但我得到了同样的错误。我能做什么?

请您参考如下方法:

这是您问题的答案:

当您使用 Selenium 3.4.0 时,IEDriverServer 3.4.0 与 IE(v 10/11) 错误:“无法在关闭的窗口上找到元素” 可能由于 Internet Explorer 的一些限制而发生 和 IEDriverServer.exe。为了防止这些错误,我们可以通过 DesiredCapabilities 类将 nativeEvents 和 requireWindowFocus 显式设置为 true,如下所示:

caps = DesiredCapabilities.INTERNETEXPLORER 
caps['ignoreProtectedModeSettings'] = True 
caps['nativeEvents'] = True 
caps['ignoreZoomSetting'] = True 
caps['requireWindowFocus'] = True 
caps['InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS'] = True 
ie = webdriver.Ie(capabilities=caps) 

As you are facing issue on Windows 7 the documentation mentions the following points: On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode".

您可以在此 link 中找到有关这些事实的更多文档.

如果这回答了您的问题,请告诉我。