Skip to main content
 首页 » 编程设计

python之使用 Selenium 和 ng-file-upload 自动上传文件

2025年05月04日19zlslch

我有一个项目,我通过 ng-file-upload 上传照片我需要使用 Python 中的 selenium webdriver 自动执行上传过程。

我的 HTML 元素如下所示:

<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”一样)

注意没有

<input type="file"/>  

使用这种上传文件的方法。

关于如何使用 Selenium 在 Python 中执行此操作的任何想法?谢谢!

请您参考如下方法:

必须有一个隐藏的文件输入,它隐含地负责文件上传。例如,angular-file-upload DEMO 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") 

结果为: