Selenium 文件上传 url "path is not absolute"

Selenium file upload url "path is not absolute"

我正在尝试使用 selenium chromedriver 将文件上传到 Facebook 群组。

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")

但是它抛出这样的异常:

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

我在 Windows 10,Chrome 44.0.2403.130,Chrome驱动程序 2.16.333243,selenium 2.47.1

那么如何从 url 上传图片? (无需明确下载)

不行,这样你只能从本地机器上传文件:

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

先下载图片,再上传。例如:

带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)

有请求

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()

使用像 "C:\Users\Casper\Desktop\hello.jpg" 这样的完整路径而不是 "hello.jpg"