June 14, 2020

Selenium Python Tutorial 6 | iFrame Frame and Alert

This is the next tutorial in the Selenium Python Tutorials for Beginners. This Selenium Python beginner tutorial explains how to handle selenium python frames and selenium python alert handling. A frame or iFrame is a smaller web page within the main web page. Selenium WebDriver cannot directly find a web element that is inside a frame. It raises the unable to find element exception. Therefore, you need to switch to the frame and then find the web element. An alert is a message box that pops up on the web page. Selenium WebDriver can dismiss or accept the alert. First, view the Selenium Python iFrame Alert Tutorial below. Then read on.

Here is my full Selenium Python example. I have put explanations in the comments within the code (lines or phrases starting with #).

# Selenium WebDriver Python coding
from selenium import webdriver
from selenium.webdriver.common.by import By
# Import two libraries needed for WebDriverWait Python
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E
import time

exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
URL = "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert"
# Selenium Python iframe locator on the web page
frame_id_locator = "iframeResult"
button_css_locator = "body > button:nth-child(2)"
wait_time_out = 5

driver = webdriver.Firefox(executable_path=exec_path)
driver.get(URL)

# Selenium WebDriver code to find all the frames on the web page:
frames = driver.find_elements_by_tag_name("iFrame")
print("There are",len(frames),"frames on this web page.")
for f in frames:
    print("Frame Id:", f.get_attribute('id'), ",Frame Name:", f.get_attribute('name'), ",Frame Source:", f.get_attribute('src'))

wait_variable = W(driver, wait_time_out)
# Selenium Python iframe switch after waiting for the frame to be available
wait_variable.until(E.frame_to_be_available_and_switch_to_it(frame_id_locator))
wait_variable.until(E.presence_of_element_located((By.CSS_SELECTOR, button_css_locator))).click()
# Wait for the alert to appear.
wait_variable.until(E.alert_is_present())
time.sleep(2)
# Accept the Python Selenium alert.
driver.switch_to.alert.accept()
time.sleep(2)
# From selenium python iframe switch back to the main web page.
driver.switch_to.default_content()

Want to learn more and see Selenium WebDriver in action? Then, please view my Selenium Python Frames Alerts Tutorial. Thank you.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.