Handle frames in Playwright-Python

Tutorial 12​​ ​​ Handle frames​​ in Playwright-Python​​ 

What you will Learn​​ in this​​ blog:

  • Handle frames​​ in Playwright-Python

  • Code snippet

Handle frames in Playwright-Python

A frame is simply an html​​ page​​ embedded​​ within​​ another​​ page.​​ 

Go to​​ https://paytm.com/​​ & click ‘Sign In’.

A separate window opens up and this is frame. Now how do we know that it is a frame?​​ 

When we​​ right click​​ this window, we can​​ see ‘View frame source’

We will not see ‘View frame source’ option if we click anywhere outside this window

So this was a basic understanding of frame.​​ 

Let us now launch​​ an iframe

https://the-internet.herokuapp.com/iframe​​ 

Let us see how to automate a test that will write inside the text area of above frame.

Inspect the text area of this frame.​​ 

Notice below that it is represented by tag ‘iframe’​​ having the ‘id’​​ mce_0_ifr​​ as shown below

In playwright-python, we have ‘frame_locator’ method as shown below. Using this method, we can identify the above frame that we have inspected​​ 

So we can write as shown below. We are using the css selector to identify the frame

Next,​​ this frame is inside a parent html page and we can locate this using the ‘html’ locator

Next, once we have located the frame, we have to click it before we start typing into it​​ 

Now, we can finally type something into the text area

So the​​ code​​ snippet​​ looks like below

Save and run the​​ script

Notice below that the desired text gets typed in the frame’s text area

This is how we can work with frames in playwright.​​ 

Note: In playwright, we do NOT have to switch to a frame (like in selenium).​​ 

Refer​​ https://playwright.dev/python/docs/api/class-frame​​ to learn more about frames

Code snippet

import​​ time
import​​ re
from​​ playwright.sync_api​​ import​​ Playwright,​​ sync_playwright,​​ expect


def​​ run(playwright: Playwright) ->​​ None:
 ​​ ​​ ​​​​ browser = playwright.chromium.launch(
headless=False)
 ​​ ​​ ​​​​ context = browser.new_context()


 ​​ ​​ ​​​​ page = context.new_page()

 ​​ ​​ ​​​​ page.goto(
"https://the-internet.herokuapp.com/iframe")

 ​​ ​​ ​​​​ frame1 = page.frame_locator("#mce_0_ifr").locator("html")
 ​​ ​​ ​​​​ frame1.click()


 ​​ ​​ ​​​​ frame1.type(
"Welcome to playwright")

 ​​ ​​ ​​​​ page.wait_for_timeout(
4000)

 ​​ ​​ ​​​​ 
# ---------------------
 ​​ ​​ ​​​​ 
context.close()
 ​​ ​​ ​​​​ browser.close()



with​​ sync_playwright()​​ as​​ playwright:
 ​​ ​​ ​​​​ run(playwright)

 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 31st DEC 2024