Search code examples
pythonplaywright

Playwright Python: Click Specific from Multiple Button


I want to Automate Fill Form using Playwright Python version. On Playwright NodeJS, I've been successfully to do the desired. Only when Porting the JS Script into Playwright Python API, it's kinda different.

The Web has Multiple Button (Submit and Random) with different Name. I can achieve both Button via get_by_role but I have no idea to get into Specific Submit Button:

#HTML
<form method="post" action="?query=MyAPI" enctype="multipart/form-data">
            <table style="width: 100%">
                <tbody><tr>
                    <td style="width: 146px">URL:</td>
                    <td><input name="url" type="text" style="width: 100%"></td></tr>

                    <tr><td style="width: 146px">&nbsp;</td>
                    <td><br>
                        <input name="Random" type="random" value="Random" style="width: 97px">
                        <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <input name="Submit" type="submit" value="Submit" style="width: 157px">
                            &nbsp; </span>
                    </td></tr>
            </tbody></table>
        </form>

#JS Version
await page.getByRole('button', { name: 'Submit' }).click();

It seems the Python Version don't have { name: 'Submit'} feature, so I can only do ('button'). I'm not sure if I left something from the API, Already tried the following things but to not avail.

page.get_by_role('button').get_by_text('Submit').click()
page.get_by_role('button', {'name': 'Submit'}).click()

EDIT2 It's a Public UR, Here's The Submit Button XPath: /html/body/div[1]/div[2]/div[2]/article[1]/form/table/tbody/tr[2]/td[2]/span/input

EDIT1: The Button is a part of Multipart Forms, it has no ID so I can't find any Alternative solution. Button Image


Solution

  • Try with:

    await page.locator('//input[@value="Submit"]').click();
    

    Or

    await page.locator('//input[@type="submit"]').click();
    

    Or

    await page.locator('//input[@name="Submit1"]').click();
    

    Then you are trying with Xpath, which should be enough if that is the only submit value/name/type of the page.

    Basically with .locator you are locating the element and then with .click() you are making click on that element previously located

    Fully working example

    from playwright.sync_api import sync_playwright
    import time
    
    def run(playwright):
        chrome = playwright.chromium
        browser = chrome.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()
        page.goto("https://suip.biz/?act=iscloudflare")
        page.locator("//input[@name='url']").fill("google.com")
        page.locator("//input[@value='Submit']").click()
        time.sleep(10)
        browser.close()
    
    with sync_playwright() as playwright:
        run(playwright)