如何使用 Python 和 Selenium 发送 ESC 键来关闭弹出窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41649916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:21:26  来源:igfitidea点击:

How to send ESC key to close pop up window using Python and Selenium?

pythonpython-3.xseleniumselenium-webdriver

提问by Volatil3

As mentioned, is there a way to send global ESCkey to close popup(CSS MODAL Window)? I tried following but did not work:

如前所述,有没有办法发送全局ESC密钥来关闭弹出窗口(CSS MODAL Window)?我尝试了以下但没有奏效:

driver.find_element_by_tag_name('body').send_keys(Keys.ESCAPE)

I know I can use xPath etc but issue is the site has dynamic elementIds and classnames.

我知道我可以使用 xPath 等,但问题是该站点具有动态 elementIds 和类名。

回答by MrHant

You don't need to send keys to the element, you need to press them globally (to browser).

您不需要向元素发送键,您需要全局按下它们(到浏览器)。

You can do it via Actions.

您可以通过操作来完成。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()

You can see more info in Webdriver API - 7.2 Action Chainsdoc

您可以在Webdriver API - 7.2 Action Chainsdoc 中看到更多信息

回答by James

I code my Selenium Python scripts in the AppRobotic Personal editor, and just insert its Windows macro functionality in between Selenium actions.

我在 AppRobotic Personal 编辑器中编写我的 Selenium Python 脚本,并在 Selenium 操作之间插入其 Windows 宏功能。

import win32com.client
x = win32com.client.Dispatch("AppRobotic.API")
from selenium import webdriver

x.Type("{ESCAPE}")

回答by Jovy Postrado

try also this it will go back to the previous driver u had

也试试这个它会回到你以前的驱动程序

driver.back()