Search code examples
pythonplaywright

Uploading an image to a website with Playwright


I'm trying to click the button upload an image to this website: https://prnt.sc/ But it seems like there is not even a [button], so can I even click anything? Is this even possible? Super confused.

There's lots of documentation on how to do this with selenium, but not much for Playwright unfortunately.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=50)
    page = browser.new_page()
    page.goto("https://prnt.sc/")
    page.locator("class=uploader__browse_button").click()

I am not using page.click because there is no button. (From what I can see) I still get errors using this code.

I've gone through the websites code and found

<form action="https://prntscr.com/upload.php" method="post" id="fileupload">

Hopefully that helps.

Solution

  • Just use set_input_files. Here is an example:

    from playwright.sync_api import sync_playwright
    
    with sync_playwright() as p:
        browser = p.webkit.launch()
        page = browser.new_page()
        page.goto('https://prnt.sc/')
        # click on AGREE privacy
        page.click('button[mode="primary"]')
        # set file to form field
        page.set_input_files('input[type="file"]', 'FULL_PATH_TO_FILE_HERE')
        # wait for a link after upload
        link = page.wait_for_selector('#link-textbox', state='visible').inner_text()
        print(f'file link: {link}')
        page.screenshot(path='example.png')
        browser.close()