python - 使用Python通过selenium Webdriver中的Url上传图像

标签 python selenium selenium-webdriver

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

有什么办法可以实现这一点吗?

[ERROR] selenium.common.exceptions.InvalidArgumentException: Message: File not found: https://ercess.com//images//events//-Blockchain-2019-36613-banner.png

最佳答案

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

您可以使用请求:

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")
<小时/>

或者您可以使用Legacy interfaceurllib 中,您将使用 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

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 - 使用Python通过selenium Webdriver中的Url上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54670988/

相关文章:

python - 随机替换python字典中的2个值

python - 如果我的 chromedriver 与 chrome 版本不兼容,我该如何修复它?

python - 贝叶斯神经网络 : Computation of Hessian

python - 如何在 Django Admin 中使用 can_add_related

python - 使用 pdb 调试 flask

c# - 浏览器打开,但无法加载本地主机页面——Selenium、MVC、C# .NET

java - 如何使用 Maven 通过注释值搜索并运行 TestNG 测试方法?

java - 使用 Selenium Webdriver 在网页中移动鼠标

java.lang.IllegalArgumentException : Sheet index (26) is out of range (0. .2)

c# - Selenium c# : Wait Until Element is Present Without Waiting the Time Given, 否则超时