SoFunction
Updated on 2025-03-03

Python Playwright performs common page interaction operations

Page interaction is one of the core operations when using Playwright for web automation. Whether it is accessing pages, waiting for elements to load, taking screenshots, or automatically filling in forms, Playwright provides a wealth of APIs to help implement these features. This article will provide a detailed introduction to how to use Playwright for common page interactions and gain insight into the browser context and its applications in handling logins and session management.

Visit page: goto()

The goto() method is the main method for accessing web pages in Playwright. Not only can it be used for simple page navigation, it also supports many advanced options such as handling page jumps and timeouts.

Basic use

Through the () method, you can navigate to a specified URL. Playwright will wait for the main content of the page to load and continue to perform subsequent operations.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = (headless=False)  # Start the browser    page = browser.new_page()  # Open a new page    ('')  # Visit the web page    print(())  # Output page title    ()

The above code will open in the browser and output the page title.

Advanced Options

You can provide more options for the goto() method to control page loading behavior:

  • timeout: Set the timeout time (in milliseconds), an error will be thrown after this time.
  • wait_until: Sets the conditions for the page loading to complete, such as load (waiting for full load), domcontentloaded (waiting for DOM content to load), networkidle (waiting for network idle), etc.

Example:

('', timeout=10000, wait_until='networkidle')

In this example, the goto() method will wait for the network to be idle and set a timeout of 10 seconds.

Wait for element loading: wait_for_selector()

During the page loading process, some elements may not be rendered immediately. At this time, using the wait_for_selector() method can help us wait for a specific element to appear or disappear.

Basic use

wait_for_selector() Wait until an element in the page appears before continuing to perform subsequent operations.

('')
page.wait_for_selector('h1')  # Wait for the h1 element to appearprint(())

In the above code, Playwright will wait for the <h1> element in the page to load before outputting the page title.

Advanced use

You can add more parameters to wait_for_selector() to specify conditions, such as:

  • state: You can specify the state of waiting elements, such as visible, hidden, attached, and detached.
  • timeout: Set the waiting timeout time, and an exception will be thrown when the timeout is timeout.

For example, wait for a button to become visible:

page.wait_for_selector('button#submit', state='visible', timeout=5000)

Page screenshot: screenshot()

Playwright provides a built-in screenshot() method, which can be very convenient to screenshot the current page or specific elements.

Page screenshot

You can use the screenshot() method to take a screenshot for the entire page and save the screenshot as a PNG file.

('')
(path='')  # Save screenshot

Element screenshot

If you only want to screenshot a specific element in the page, you can also use the screenshot() method. After selecting an element using locator(), call screenshot():

element = ('h1')
(path='')

This will take a screenshot of the <h1> element in the page and save it as a file.

Advanced Options

The screenshot() method also provides some useful parameters, such as:

  • full_page: If True, Playwright will intercept the entire page, including the part after the page is scrolled.
  • quality: You can specify the quality of JPEG screenshots (PNG format does not support).
(path='', full_page=True)

Fill the form: fill()

fill() is a method used by Playwright to automatically fill in the form input box. It accepts two parameters: the selector and the input value.

Basic use

The following code example shows how to fill out a login form:

('/login')
('input[name="username"]', 'myusername')  # Fill in the user name('input[name="password"]', 'mypassword')  # Fill in your password('button[type="submit"]')  # Submit the form

Fill in the drop-down menu and check boxes

For checkboxes and drop-down menus, Playwright provides the check() and select_option() methods.

Check box action:

('input[name="agree"]')  # Check the check box

Drop-down menu operation:

page.select_option('select[name="options"]', 'value1')  # Select an option in the drop-down menu

Browser context: Handle login or session management

Browser Context is a powerful feature in Playwright that allows us to create multiple independent session environments in the same browser instance. Each context has its own cookies, caches, and local storage, so multiple user sessions or windows can be handled independently.

Create a new browser context

The browser.new_context() method can create a new context, each of which is independent of each other.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = ()
    
    # Create a context for user 1    context1 = browser.new_context()
    page1 = context1.new_page()
    ('/login')
    
    # Create a context for user 2    context2 = browser.new_context()
    page2 = context2.new_page()
    ('/login')

    ()

In the above code, we create separate contexts for both users, each of which can run in the same browser instance without sharing session, cookies, or local storage.

The practical application of context: login persistence

Sometimes, we need to keep the login state in different tests, and we can use the context storage_state to save and load the session.

Save session status:

context = browser.new_context()
page = context.new_page()
('/login')
# Simulate login('input[name="username"]', 'myusername')
('input[name="password"]', 'mypassword')
('button[type="submit"]')
# Save login statuscontext.storage_state(path='')

Loading session status:

context = browser.new_context(storage_state='')  #Loading the login statuspage = context.new_page()
('/dashboard')  # Go directly to the page after login

Using the context's storage_state() method, you can save cookies and local storage in the current session and load this data in subsequent tests to achieve seamless login persistence.

Summarize

This article introduces how to use Playwright for basic page interaction, including accessing pages, waiting for elements to load, page screenshots, and filling forms. At the same time, we also explored in detail the concept of browser context and how to use it to handle multi-user login and session management. With these basic operations, you can build feature-rich automation scripts and handle complex user sessions in testing.

This is the end of this article about Python Playwright's common page interaction. For more related Python Playwright page interaction content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!