How To Change HTML in Playwright Using Python

QASource Engineering Team | March 10, 2025

How to Change HTML in Playwright Using Python

Playwright is a robust automation framework for testing web applications. It allows developers and testers to interact with web pages dynamically. One helpful feature is the ability to modify the HTML content of a webpage using JavaScript execution. This can be helpful for testing UI behavior, validating dynamic content updates, or simulating real-time changes. Here are a few methods for changing HTML in Playwright using Python.

  1. Using evaluate to modify innerHTML:
    from playwright.sync_api import sync_playwright
    
    with sync_playwright() as p:
    	browser = p.chromium.launch()
    	page = browser.new_page()
    	page.goto("https://example.com")
    
    	# Change HTML content
    	page.evaluate("document.body.innerHTML = '<h1>New Content</h1>'")
    
    	browser.close()    
    
  2. Using evaluate to modify an element’s content:
    page.evaluate("document.querySelector('div').innerHTML = 'Updated Content'")
  3. Using locator and set_inner_html:
    page.locator("div").set_inner_html("<p>Updated Content</p>")

Conclusion

Modifying HTML in Playwright using Python provides flexibility when automating web applications. Whether using evaluate to execute JavaScript or set_inner_html to update elements, these methods help test dynamic content changes efficiently. With Playwright's capabilities, testers can validate UI interactions and ensure smooth user experiences.

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment

Categories