Automate file upload using Selenium and ng-file-upload

一个人想着一个人 提交于 2019-12-05 07:28:43

问题


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.

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>

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)

Note that there is no

<input type="file"/> 

with this method of uploading a file.

Any ideas how to do this in Python using Selenium? Thanks!


回答1:


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.

Here is a working example:

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

Results into:



来源:https://stackoverflow.com/questions/32590676/automate-file-upload-using-selenium-and-ng-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!