Software Dev and QA Tips

How To Change HTML With Python in Playwright?

Written by QASource Engineering Team | Mar 10, 2025 4:00:00 PM

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.