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!