Search code examples
pythonwebautomationplaywrightplaywright-python

Using Playwright for Python, how can I wait for a field / selector result to change


Using Playwright for Python, I want to wait for a change of content.

I can get the content of a selector like this

month = page.querySelector('.day__month_btn').innerText()

In this example, I'm reading the month value of a datepicker element and want to select the next month. Then wait, until the month has changed.

To change the month, I can click on the next month icon

page.querySelector('.next').click()

I now want to wait until the click is accepted.

A hacky way is to wait is to repeatedly grab the value until it changes

while True:
    if page.querySelector('.day__month_btn').innerText() != month:
        break
    time.sleep(0.2)  

In a real world, I'd also need check for timeouts.

Is there a better way to do this?


Solution

  • You can use waitForFunction:

    month = page.querySelector(".day__month_btn").innerText()
    page.waitForFunction("document.querySelector('.day__month_btn').innerText() !== '" + month + "'")