In this post, we will learn how to upload a file using Selenium Webdriver in Python as well as using the SeleniumBase framework. File uploads are common use cases for the majority of websites these days, so it is important to know how to work with them.
Typically, you’ll run into two scenarios when working with file uploads. 1 – where the file input field is visible. 2 – where the file input field is hidden (most common in modern websites). Let’s take a look at an example for both of them –
Upload file on a visible input field
For this example, I will be using this website – https://the-internet.herokuapp.com/upload
As you can see in the screenshot above, the “Choose File” input field is visible. So, in this case, we can easily find the input field and send the file to that.
def test_visible_upload(self): # open page self.open("https://the-internet.herokuapp.com/upload") # get file path file_path = './data/logo.jpg' # upload file self.choose_file("#file-upload", file_path) # click the upload button self.click("#file-submit") # assert file uploaded text self.assert_text("File Uploaded!", "h3")
Upload file on a hidden input field
However, most likely, you will see in the modern websites that the file input field is hidden for styling purposes. Every website will have its own kind of implementation to hide the input field, example – reducing opacity to 0, setting display to none etc…
For this example, we will be using this website – https://practice.automationbro.com/cart/
As you can see in the screenshot above, we do not see any “Choose File” input field as that is hidden behind the “Select File” button.
Solution: So to overcome this problem, we need to make the element visible again by manipulating the DOM using JavaScript.
def test_hidden_upload(self): # open page self.open("https://practice.automationbro.com/cart/") # get file path file_path = './data/logo.jpg' # add js code remove_hidden_class = "document.getElementById('upfile_1').classList.remove('file_input_hidden')" self.add_js_code(remove_hidden_class) # upload file self.choose_file('#upfile_1', file_path) # click the upload button self.click("#upload_1") # assert file uploaded text self.assert_text("uploaded successfully", "#wfu_messageblock_header_1_label_1")
The key thing to notice here is the add js code
part where I am removing the hidden class to enable our input field and then uploading the file.
Check out the video below to learn how to effectively upload file in Selenium Python –
I hope this post helped you out, let me know if you have any questions in the comments below!
Happy testing!