使用Python通过Selenium Webdriver中的Url上传图像 [英] Upload Images through Url in selenium Webdriver using Python

查看:191
本文介绍了使用Python通过Selenium Webdriver中的Url上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

driver.find_element(By.XPATH, "//*[@id='upl-zone']/input").send_keys("https://ercess.com//images//events//-Blockchain-2019-36613-banner.png")

有什么办法可以使它工作?

Is there any way to make that work ?

[错误] selenium.common.exceptions.InvalidArgumentException:消息:未找到文件:

推荐答案

您首先需要将图像下载到计算机上,然后将其上传...

You first need to download the image to your computer and then upload it...

您可以使用requests:

import requests

URL = "https://ercess.com//images//events//-Blockchain-2019-36613-banner.png"
picture_req = requests.get(URL)
if picture_req.status_code == 200:
    with open("/path/to/image.jpg", 'wb') as f:
        f.write(picture_req.content)

然后发送/path/to/image.jpg:

driver.find_element(By.XPATH, "//*[@id='upl-zone']/input").send_keys("/path/to/image.jpg")


或者您可以使用 urllib中的> ,您将使用urlretrieve:


Or you can use the Legacy interface of urllib you will use urlretrieve:

import urllib.request

URL = "https://ercess.com//images//events//-Blockchain-2019-36613-banner.png"
urllib.urlretrieve(URL, "file_name.png")
driver.find_element(By.XPATH, "//*[@id='upl-zone']/input").send_keys("file_name.png")

要使用send_keys将路径发送到文件,可以使用 pathlib

To send the path to the file with send_keys you can use pathlib

from pathlib import Path

# `cwd`: current directory is straightforward
cwd = Path.cwd()
# using "F"string for format you can use: image_file_name = str(cwd) + "\" + "file_name.png" 
image_file_name = fr"{cwd}\file_name.png"
# this print is just to show the image_file_name   
print(image_file_name)

希望这对您有帮助!

这篇关于使用Python通过Selenium Webdriver中的Url上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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