使用Selenium和ng-file-upload自动上传文件 [英] Automate file upload using Selenium and ng-file-upload
问题描述
我有一个项目,我通过 ng-file-upload 上传照片,并且我需要使用Python中的Selenium Webdriver自动执行上传过程.
I have a project where I am uploading photos via ng-file-upload and I need to automate the upload process with selenium webdriver in Python.
我的HTML元素如下所示:
my HTML element looks like this:
<element
ngf-pattern="image/*" accept="image/*"
ngf-max-size="10MB" ngf-max-height="1000" ngf-select="addPhoto($index, $file)">
...</element>
手动完成元素的上传绝对可以.但是我找不到在Python中使用Selenium来自动执行此操作的方法.我试图找到该元素,然后发送图像的绝对路径的键,但这只是将绝对路径放在浏览器的搜索字段中(就像我在Mac上键入"Command + F"一样)
Uploading the element definitely works when doing it manually. But I cannot find a way to automate this using Selenium in Python. I have tried finding the element, then sending the keys of the image's absolute path, but that just puts the absolute path in the browser's search field (as if I typed "Command + F" on Mac)
请注意,没有
<input type="file"/>
使用这种上传文件的方法.
with this method of uploading a file.
有什么想法如何使用Selenium在Python中做到这一点?谢谢!
Any ideas how to do this in Python using Selenium? Thanks!
推荐答案
必须隐藏文件输入,该文件输入隐式负责文件的上载.例如, angular-file-upload
DEMO页面将其隐藏在页面底部.
There has to be a file input hidden which is implicitly responsible for the file upload. For instance, the angular-file-upload
DEMO page has it hidden at the bottom of a page.
这是一个有效的示例:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://angular-file-upload.appspot.com/")
# wait for the upload box to be visible
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[ngf-select]")))
# get a model
model = element.get_attribute("ng-model")
# find a file input by model
file_input = driver.find_element_by_css_selector('input[ngf-select][ng-model="%s"]' % model)
# upload an image
file_input.send_keys("/absolute/path/to/dr-evil-and-minion-laughing.png")
结果为:
这篇关于使用Selenium和ng-file-upload自动上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!