selenium.common.exceptions.InvalidArgumentException:消息:尝试通过硒通过 url 上传图像时找不到文件 [英] selenium.common.exceptions.InvalidArgumentException: Message: File not found while trying to upload image by url through selenium

查看:21
本文介绍了selenium.common.exceptions.InvalidArgumentException:消息:尝试通过硒通过 url 上传图像时找不到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to upload image via external url, i found examples only that shows how to upload locally stored images. This what i tried and this didn't work.

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

推荐答案

send_keys(*value)

根据 send_keys() 模拟输入元素.

  • send_keys(*value)
  • 参数:

value - A string for typing. For setting file inputs, this could be a local file path.

  • 使用它来设置文件输入:

  • Use this to set file inputs:

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

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

    But as per your code trial as you are passing an url as a string hence you see the error as:

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

    解决方案

    如果您的用例是使用Selenium上传文件,您必须在本地系统中下载文件并传递绝对路径 文件作为 send_keys() 方法中的参数.

    Solution

    If your usecase is to use Selenium for file uploading you have to have the download the file in your local system and pass the absolute path of the file as an argument within send_keys() method.

    作为替代,您也可以使用 urlretrieve 方法来自 Python 3.x 如下:

    As an alternative, you can also use urlretrieve method from Python 3.x as follows:

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

    • Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for 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")
    

    这篇关于selenium.common.exceptions.InvalidArgumentException:消息:尝试通过硒通过 url 上传图像时找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆