Skip to main content

_python

TL;DR - Show Me The Code

3-work-with-frames/code/python/frames.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

@pytest.fixture
def driver_setup_teardown():
driver = webdriver.Firefox()
yield driver
driver.quit()

def test_example_1(driver_setup_teardown):
driver = driver_setup_teardown
driver.get('https://the-internet.herokuapp.com/nested_frames')
driver.switch_to.frame('frame-top')
driver.switch_to.frame('frame-middle')
assert driver.find_element(By.ID, 'content').text == "MIDDLE", "content should be MIDDLE"

def test_example_2(driver_setup_teardown):
driver = driver_setup_teardown
driver.get('https://the-internet.herokuapp.com/tinymce')
driver.switch_to.frame('mce_0_ifr')
editor = driver.find_element(By.ID, 'tinymce')
before_text = editor.text
editor.clear()
editor.send_keys('Hello World!')
after_text = editor.text
assert after_text != before_text, "%s equals %s" % (before_text, after_text)
driver.switch_to.default_content()
assert driver.find_element(By.CSS_SELECTOR, 'h3').text != "", "h3 element should not be empty"

Code Walkthrough

Importing Libraries, Setup and Teardown

Lines 1 to 9 are pulling in our requisite libraries our testing framework (e.g., import pytest), driving the browser with Selenium (e.g., from selenium import webdriver), and a locator strategy to find the elements (e.g. from selenium.webdriver.common.by import By), and wire up some setup and teardown methods for our tests.

Example 1

Line 11 shows our first test. In it, we'll step through an example of nested frames which can be found on the-internet.

With Selenium's .switch_to.frame method we can easily switch to the frame we want. It accepts either an ID or name attribute. But in order to get the text of the middle frame (e.g., a frame nested within another frame), we need to switch to the parent frame (e.g., the top frame) and then switch to the child frame (e.g., the middle frame).

Once we've done that we're able to find the element we need, grab its text, and assert that it's what we expect.

While this example helps illustrate the point of frame switching, it's not very practical.

Example 2

Line 18 shows a more likely example you'll run into -- working with a WYSIWYG Editor like TinyMCE. You can see the page we're testing on the-internet.

Executing the Test

Before executing the test, we need to install the required libraries. We can do this by running pip install -r requirements.txt from the command-line. The requirements.txt file contains the libraries we need to install.

Toggle to see the requirements.txt file.
3-work-with-frames/code/python/requirements.txt
selenium==4.24.0
pytest

After installing the required libraries, we can run the test by executing pytest frames.py from the command-line.