Search code examples
pythonseleniumwebdriverselenium-chromedriver

Selenium file upload url "path is not absolute"


I'm trying to upload a file to a facebook group with selenium chromedriver.

driver.find_element_by_xpath("//input[@type='file']").send_keys("http://www.peta.org/wp-content/uploads/2013/10/goat_2D00_list_2D00_1.jpg")

But It throws an Exception Like this:

selenium.common.exceptions.WebDriverException: Message: unknown error: path is not absolute:

I'm on Windows 10, Chrome 44.0.2403.130, ChromeDriver 2.16.333243, selenium 2.47.1

So how I can upload images from urls ? (without having to explicitly download it)


Solution

  • Nope, this way you can only upload files from a local machine:

    driver.find_element_by_xpath("//input[@type='file']").send_keys("/Path/to/the/file")
    

    Download the image first, then upload. For instance:

    With urllib

    import os
    import urllib
    
    base_dir = "/Path/to/dir/"
    path_to_image = os.path.join(base_dir, "upload.jpg")
    
    urllib.urlretrieve("http://www.peta.org/wp-content/uploads/2013/10/goat_2D00_list_2D00_1.jpg", path_to_image)
    
    driver.find_element_by_xpath("//input[@type='file']").send_keys(path_to_image)
    

    With requests

    import os
    import requests
    
    base_dir = "/Path/to/dir/"
    path_to_image = os.path.join(base_dir, "upload.jpg")
    
    response = requests.get("http://www.peta.org/wp-content/uploads/2013/10/goat_2D00_list_2D00_1.jpg")
    
    if response.status_code == 200:
        f = open(base_dir + path_to_image, 'wb')
        f.write(response.content)
        f.close()