Search code examples
pythonplaywrightplaywright-python

playwright python not able to select by class


I have the following element in a website that i want to fill in but for the life of me i cant get the script to actually "locate" it, i get timeout error even though the main page has been fully loaded (non-headless browser so i am certain all elements have been fully loaded). is there anyway i can select the element using the multiple css classes in the element? Element:

<input type="text" id="keyword" formcontrolname="companyName" maxlength="35" class="form-control ng-untouched ng-pristine ng-valid" placeholder="Type Company Name">

my code for selecting using classes (doesnt work):

ric = 'ITUB'
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
url = 'https://www.b3.com.br/en_us/products-and-services/trading/equities/listed-companies.htm?codigo=19623'

async with async_playwright() as P:
    browser = await P.chromium.launch(channel='chrome', headless=False)
    page: Page = await browser.new_page(user_agent=user_agent)
    await page.goto(url, wait_until='load')
    await page.locator('input[class=form-control ng-untouched ng-pristine ng-valid]').fill(ric)
    await page.get_by_role("button", name="Search").click()
    await page.screenshot(path="screenshot.png")

I tried to select it using chained locators for the parent divs, placeholders, by its role, and id but i keep getting timeout error.


Solution

  • Those elements are inside the iframe bvmf_frame. You need to locate the frame first.

    async with async_playwright() as P:
        browser = await P.chromium.launch(channel='chrome', headless=False)
        page: Page = await browser.new_page(user_agent=user_agent)
        await page.goto(url, wait_until='load')
        frame = page.frame_locator("#bvmf_iframe")
        await frame.get_by_role("textbox", name="Type Company Name").fill(ric)
        await frame.get_by_role("button", name="Buscar", exact=True).click()
        await page.screenshot(path="screenshot.png")