How to extract text from a Javascript alert in Selenium with python?


We can extract text from a Javascript alert with the help of text method under Alert class. The alerts are basically the browser popups that are triggered for either dismissing or accepting the data entered.

All these actions are performed by Selenium with the help of class selenium.webdriver.common.alert.Alert(driver). It has the methods to extract the text on a particular alert, accepting and dismissing these pop ups of the browser.

The elements on the alert cannot be identified by simply spying them from the html code. This is because these are considered implemented by Javascript.

Selenium alert methods are listed below −

  • accept() – This method accepts an alert pop up.

Syntax

a = Alert(driver)
a.accept()
  • dismiss() – This method dismisses an alert pop up.

Syntax

a = Alert(driver)
a.dismiss()
  • send_keys(value) – This method keys in text on alert pop up.

Syntax

a = Alert(driver)
a.send_keys("Yes")
  • text – This method extracts text from the alert pop up.

Syntax

a = Alert(driver)
print(a.text)
  • switch_to.alert – This method switches focus to alert.

Syntax

a = driver.switch_to.alert

Example

Code Implementation for extracting text from an alert.

from selenium import webdriver
from selenium.webdriver.common.alert import Alert
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
#click on submit button
driver.find_element_by_xpath("//button[@name='submit']").click()
a = driver.switch_to.alert
# printing the alert text in console
print(a.text)
# dismissing the alert pop up
a.dismiss()
#to close the browser
driver.close()

Updated on: 29-Jul-2020

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements