'Using playwright for Python, how do I wait for two different selectors/handles at the same time and take the first successful match?

using Playwright for Python, I need to catch if a page displays a winner or a loser message.

I can wait for a winner message to appear like this:

new_selector = "text=Your are a winner"
page.wait_for_selector(new_selector)
handle = query_selector(new_selector)
# do something with handle

But what can I do to wait for two different things? (Not only text but any kind of selector)

I could try an endless loop:

new_selector1 = "text=Your are a winner"
new_selector2 = "text=Better luck next time"

while True:
    handle = query_selector(new_selector1)
    if handle:
        break  
    handle = query_selector(new_selector2)
    if handle:
        break   
    time.sleep(0.25) 
    # write my own timeout here

# do something with handle

But is there something in playwright that allows me to wait for two handles and take the first match?



Solution 1:[1]

You can pass both selectors separated by a comma. Ref.

new_selector = "text=Your are a winner, text=Better luck next time"
handle = query_selector(new_selector)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hardkoded