'How to open the latest downloaded file

This is the code immediately before I get stuck:

#Start a new post
driver.find_element_by_xpath("//span[normalize-space()='Start a post']").click()
time.sleep(2)
driver.find_element_by_xpath("//li-icon[@type='image-icon']//*[name()='svg']").click()
time.sleep(2)

The above code works well. The next step though has me puzzled.

I would like to upload the latest image file from my downloads folder. When I click on the link above in LinkedIn it navigates to my user folder (Melissa). (see image)

So... I'm looking for the next lines of code to navigate from the default folder to the Downloads folder (C:\Users\Melissa\Downloads), then, select the newest file, then click 'open' so it attaches to the LinkedIn post.

enter image description here



Solution 1:[1]

You can upload the image using this method:

import getpass, glob, os

# Replace this with the code to get the upload input tag
upload_button = driver.find_element_by_xpath("//input[@type='file']")

# Get downloads
downloads = glob.glob("C:\\Users\\{}\\Downloads\\*".format(getpass.getuser()))

# Find the latest downloaded file
latest_download = max(downloads, key=os.path.getctime)

# Enter it into the upload input tag
upload_button.send_keys(latest_download)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman