Volatil3
Volatil3

Reputation: 14988

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

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.

Upvotes: 34

Views: 77970

Answers (4)

robertspierre
robertspierre

Reputation: 4371

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()

Upvotes: 2

James
James

Reputation: 37

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}")

Upvotes: -2

Jovy Postrado
Jovy Postrado

Reputation: 1

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

driver.back()

Upvotes: -5

MrHant
MrHant

Reputation: 920

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

Upvotes: 74

Related Questions