Search code examples
pythondrop-down-menuplaywrightplaywright-python

Using python playwright to select a value from a select dropdown


I'm trying to select a value from drop-down menu with python playwright but it doesn't work. screenshot of dropdown

I successfully can get the value from the three first, but that one with label "Mês" simply doesn't work.

Here is the code

from playwright.sync_api import sync_playwright, Playwright

with sync_playwright() as p:
    nav = p.chromium.launch(headless=False)

    page = nav.new_page()

        page.goto('https://www4.trf5.jus.br/diarioeletinternet/paginas/consultas/consultaDiario.faces;jsessionid=A7EF0E11BE9943A9942B54CE45F7C7F9')

    page.locator("[name='frmVisao:orgao']").select_option('Seção Judiciária do Sergipe')
    page.locator("[name='frmVisao:edicao']").select_option('Administrativo')
    page.locator("[name='frmVisao:periodo']").select_option('2021')
    page.locator('xpath=//*[@id="frmVisao:meses"]').select_option('03')

    page.wait_for_timeout(5000)


    nav.close()

Does anyone know what I'm doing wrong?

Here is the site: https://www4.trf5.jus.br/diarioeletinternet/paginas/consultas/consultaDiario.faces.


Solution

  • Your code works consistently for me. Those meses options are populated once you select the other fields, so you could use wait_for_function() to wait until the months populate, to avoid a race condition:

    from playwright.sync_api import sync_playwright  # 1.40.0
    
    
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()
        page.goto("<Your URL>")
        page.locator("[name='frmVisao:orgao']").select_option("Seção Judiciária do Sergipe")
        page.locator("[name='frmVisao:edicao']").select_option("Administrativo")
        page.locator("[name='frmVisao:periodo']").select_option("2021")
        page.wait_for_function("""
            document
              .querySelectorAll('[name="frmVisao:meses"] option')
              .length > 11
        """)
        page.locator('[name="frmVisao:meses"]').select_option("03")
        page.screenshot(path="verify.png")
        browser.close()
    

    A more precise (and probably better) condition would be to block until the exact option for March is available:

    page.wait_for_function("""
        document.querySelector('[name="frmVisao:meses"] option[value="03"]')
    """)