Remove focus using ‘blur’ method and ‘clear’ method in Playwright Python

Tutorial 21​​ ​​ Remove focus using ‘blur’ method​​ and ‘clear’ method​​ in​​ Playwright​​ Python​​ 

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

  • blur method

  • ‘clear’ method

  • Code snippet

Usage of blur method​​ ​​ 

Let us try to execute below script

Notice that the letters were typed in the search field. We did not have to ask playwright to focus on the search field. The focus on the search field is by default​​ 

We can remove the focus from the search field by using​​ the ‘blur’ method

Execute, notice that the script did NOT type the above letters. The reason being, the focus has​​ now​​ been removed from the search field

‘clear’ method​​ 

We can use the ‘clear’ method to clear the text that playwright has typed

Execute test

Notice that, first playwright types some text and then it clears the text


Code snippet​​ (blur method)

import​​ time

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://www.google.com/")

 ​​ ​​ ​​​​ page.keyboard.press(
'w')
 ​​ ​​ ​​​​ page.keyboard.press(
'a')
 ​​ ​​ ​​​​ page.keyboard.press(
'y')
 ​​ ​​ ​​​​ page.keyboard.press(
'2')
 ​​ ​​ ​​​​ page.keyboard.press(
'a')
 ​​ ​​ ​​​​ page.keyboard.press(
'u')
 ​​ ​​ ​​​​ page.keyboard.press(
't')

 ​​ ​​ ​​​​ page.locator(
"#input").blur()

 ​​ ​​ ​​​​ page.keyboard.press(
'o')
 ​​ ​​ ​​​​ page.keyboard.press(
'm')
 ​​ ​​ ​​​​ page.keyboard.press(
'a')
 ​​ ​​ ​​​​ page.keyboard.press(
't')
 ​​ ​​ ​​​​ page.keyboard.press(
'i')

 ​​ ​​ ​​​​ time.sleep(
6)

 ​​ ​​ ​​​​ page.wait_for_timeout(
5000)

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



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

 

Code snippet (clear method)

import​​ time

from​​ playwright.sync_api​​ import​​ Page,​​ expect


def​​ test_example(page: Page) ->​​ None:
 ​​ ​​ ​​​​ page.goto(
"https://www.google.com/")

 ​​ ​​ ​​​​ page.get_by_title(
"Search").fill("way2automation")

 ​​ ​​ ​​​​ page.get_by_title(
"Search").clear()

 ​​ ​​ ​​​​ page.wait_for_timeout(
5000)

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