Logo New Black

Step-by-Step Guide: How to Check for Element in Playwright Effectively

Ensuring the presence of an HTML element on a webpage is a fundamental step in automated web testing. With Playwright and Python, developers can employ the page.locator() or page.is_visible() functions for this purpose. These functions offer a straightforward way to verify elements, but for those seeking to push the boundaries of web automation and testing, incorporating a web scraping API into your toolkit can be a game-changer. Such APIs augment your ability to interact with, extract, and analyze web data, thereby enriching your testing framework and providing deeper insights into web page behaviors and content accessibility.

with sync_playwright() as pw:
    browser = pw.chromium.launch(headless=False)
    context = browser.new_context(viewport={"width": 1920, "height": 1080})
    page = context.new_page()

    # go to url

    # use .locator() with CSS or XPath selectors:
    elements = page.locator("div.post-content")
    if elements.count() > 0:  
        print(f"found {elements.count()} elements")
        visible = sum([handle.is_visible() for handle in elements.element_handles()])
        print(f"out of which {visible} are visible")

It’s important to note that this method does not wait for the element to appear on the page. For information on how to wait for a page to load in Playwright, refer to the guide on our website.