selenium.common.exceptions.InvalidArgumentException:消息:尝试通过 url 通过 selenium 上传图像时找不到文件

selenium.common.exceptions.InvalidArgumentException: Message: File not found while trying to upload image by url through selenium

我需要通过外部上传图片 url,我只找到了展示如何上传本地存储图片的示例。这是我尝试过的,但没有用。

driver.find_element_by_id("attachFile_nPaintUploadAll").send_keys("http://bdfjade.com/data/out/89/5941587-natural-image-download.jpg")

错误信息:

selenium.common.exceptions.InvalidArgumentException: Message: File not found: http://bdfjade.com/data/out/89/5941587-natural-image-download.jpg

尝试先获取文件再上传:

import urllib

urllib.urlretrieve("http://bdfjade.com/data/out/89/5941587-natural-image-download.jpg", "5941587-natural-image-download.jpg")
driver.find_element_by_id("attachFile_nPaintUploadAll").send_keys("5941587-natural-image-download.jpg")

要检索 Python 3.X 中的文件,您可以尝试

urllib.request.urlretrieve("http://bdfjade.com/data/out/89/5941587-natural-image-download.jpg", "5941587-natural-image-download.jpg")

import requests

with open("5941587-natural-image-download.jpg", "wb") as f:
    f.write(requests.get("http://bdfjade.com/data/out/89/5941587-natural-image-download.jpg").content)

您可以删除文件,然后使用

import os

os.remove("5941587-natural-image-download.jpg")

send_keys(*值)

根据 send_keys() 的文档模拟输入元素。

  • send_keys(*value)
  • 参数:

    value - A string for typing. For setting file inputs, this could be a local file path.
    
  • 使用它来设置文件输入:

    driver.find_element_by_id("attachFile_nPaintUploadAll").send_keys("path/to/profilepic.gif")
    

但是根据您的代码试验,当您将 url 作为 string 传递时,您会看到错误为:

selenium.common.exceptions.InvalidArgumentException: Message: File not found: http://bdfjade.com/data/out/89/5941587-natural-image-download.jpg

解决方案

如果您的 usecase 要使用 Selenium 进行文件上传,您必须在本地系统中下载文件并通过文件的绝对路径作为send_keys()方法中的参数。


备选 (urllib.request.urlretrieve)

作为替代方案,您还可以使用 Python 3.x 中的 urlretrieve 方法,如下所示:

urllib.request.urlretrieve(url, 文件名=None, reporthook=None, 数据=None)

  • 将 URL 表示的网络对象复制到本地文件。如果 URL 指向本地文件,除非提供文件名,否则不会复制对象。 Return 一个元组 (filename, headers) 其中 filename 是可以在其下找到对象的本地文件名,headers 是 urlopen() 返回的对象的 info() 方法(对于一个远程对象)。例外情况与 urlopen().

  • 相同
  • 代码块:

    import urllib.request
    
    urllib.urlretrieve("http://andrew.com/selfie.jpg", "andrew_selfie.jpg")
    driver.find_element_by_id("attachFile_nPaintUploadAll").send_keys("andrew_selfie.jpg")