pythonplaywrightplaywright-python

How to locate elements simultaneously?


By nature, Playwright locator is blocking, so whenever it's trying to locate for an element X, it stops and waits until that element is located or it times out.

However, I want to see if it is possible to make it so that it locates two elements at once, and, if either one is found, proceed forward, based on whichever was found.

Is something like that possible in Python Playwright?

Thanks


Solution

  • or_​

    Added in: v1.33

    Creates a locator matching all elements that match one or both of the two locators.

    Note that when both locators match something, the resulting locator will have multiple matches, potentially causing a locator strictness violation.

    Usage

    Consider a scenario where you'd like to click a "New email" button, but sometimes a security settings dialog appears instead. In this case, you can wait for either a "New email" button or a dialog and act accordingly.

    note

    If both "New email" button and security dialog appear on screen, the "or" locator will match both of them, possibly throwing the "strict mode violation" error. In this case, you can use locator.first to only match one of them.

    new_email = page.get_by_role("button", name="New")
    dialog = page.get_by_text("Confirm security settings")
    expect(new_email.or_(dialog).first).to_be_visible()
    if (dialog.is_visible()):
      page.get_by_role("button", name="Dismiss").click()
    new_email.click()