32

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

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.

jww
  • 97,681
  • 90
  • 411
  • 885
Volatil3
  • 14,253
  • 38
  • 134
  • 263

4 Answers4

71

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 Chains doc

MrHant
  • 880
  • 6
  • 11
  • 5
    I had to add the import of ActionChains in order to get this to work, and just used `ActionChains(driver).send_keys(Keys.ESCAPE).perform()` without the `webdriver` bit in front. Import info here: https://stackoverflow.com/a/26669375/6163621 – elPastor Jun 13 '19 at 11:21
  • you need to import first thing you are going to work with - in this example it's either webdriver or ActionChains – MrHant Jun 14 '19 at 08:07
0

This code will send the "Esc" key in the browser window:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
def sendesc(browser):
    ActionChains(browser).send_keys(Keys.ESCAPE).perform()
robertspierre
  • 3,218
  • 2
  • 31
  • 46
  • 1
    Could you add some human explanations of your solution, please ? that would be great : ) easier to understand – snoob dogg Apr 29 '22 at 22:06
  • @snoobdogg it initialize an action chain that will send the "Esc" key to the window of the browser, and then run the action chain – robertspierre Apr 30 '22 at 05:35
-2

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

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

x.Type("{ESCAPE}")
James
  • 39
  • 2
-5

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

driver.back()
  • 1
    this is different. based on documentation `driver.back()` goes one step backward in the browser history http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.back – Panagiotis Simakis Jul 05 '18 at 12:25