【问题标题】:selenium.common.exceptions.InvalidArgumentException: Message: File not found while trying to upload image by url through seleniumselenium.common.exceptions.InvalidArgumentException:消息:尝试通过 selenium 通过 url 上传图像时找不到文件
【发布时间】:2018-12-28 08:30:15
【问题描述】:

我需要通过外部 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

【问题讨论】:

标签: python selenium selenium-webdriver webdriver urlretrieve


【解决方案1】:

尝试先获取文件再上传:

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

【讨论】:

    【解决方案2】:

    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, filename=None, reporthook=None, data=None)

    • 将由 URL 表示的网络对象复制到本地文件。如果 URL 指向本地文件,除非提供文件名,否则不会复制对象。返回一个元组 (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")
      

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2021-07-26
      • 1970-01-01
      • 2015-01-05
      • 2012-11-24
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多