Upload a file using Playwright Python

Tutorial 14​​ ​​ Upload a​​ file using Playwright​​ Python​​ 

What you will Learn​​ in this​​ blog:

  • Upload​​ a​​ file using Playwright​​ python

  • Code snippets

Upload​​ a​​ file using Playwright​​ python

Let us​​ now​​ see​​ how to​​ upload a file using PW​​ python.

We will​​ upload a​​ test​​ file​​ from our local machine​​ to​​ the below site

https://the-internet.herokuapp.com/upload​​ 

First we will​​ choose a file and click ‘Upload’.

Inspect ‘Choose File’ button

In the previous blog we had downloaded a file under ‘downloads’ folder, let us rename the file. We will upload this file ​​ 

Just like we have seen earlier, let us create ‘current working directory path’ and join this path with the file we want to upload

Now we can use the​​ set_input_files()​​ method that accepst 2 arguments: locator and filepath

Save and execute

Notice that the file can be seen next to ‘Choos File’ button

After setting the input file,​​ we will​​ click ‘Upload’ button

The​​ code snippet​​ looks like below:

Save​​ and execute.

Observe below that the file gets uploaded

This is​​ how we can upload the file using PW.

Code snippet

import​​ os

from​​ playwright.sync_api​​ import​​ Playwright,​​ sync_playwright,​​ expect


def​​ run(playwright: Playwright) ->​​ None:
 ​​ ​​ ​​​​ browser = playwright.chromium.launch(headless=False)
 ​​ ​​ ​​​​ context = browser.new_context()


 ​​ ​​ ​​​​ page = context.new_page()

 ​​ ​​ ​​​​ page.goto(
"https://the-internet.herokuapp.com/upload")

 ​​ ​​ ​​​​ current_working_dir = os.getcwd()

 ​​ ​​ ​​​​ file_path = os.path.join(current_working_dir
,​​ "downloads/fileToUpload.txt")

 ​​ ​​ ​​​​ page.set_input_files(
'#file-upload',​​ file_path)

 ​​ ​​ ​​​​ page.locator(
"text = Upload").last.click()

 ​​ ​​ ​​​​ page.wait_for_timeout(
10000)

 ​​ ​​ ​​​​ 
# ---------------------
 ​​ ​​ ​​​​ 
context.close()
 ​​ ​​ ​​​​ browser.close()



with​​ sync_playwright()​​ as​​ playwright:
 ​​ ​​ ​​​​ run(playwright)

 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 10th Nov 2024