場景
文件上傳操作也比較常見功能之一,上傳功能操作webdriver 並沒有提供對應的方法,關鍵上傳文件的思路。
上傳過程一般要打開一個系統的window 窗口,從窗口選擇本地文件添加。所以,一般會卡在如何操作本地window 窗口。其實,上傳本地文件沒我們想的那么復雜;只要定位上傳按鈕,通send_keys 添加本地文件路徑就可以了。絕對路徑和相對路徑都可以,關鍵是上傳的文件存在。
代碼
upload_file.html
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>upload_file</title> <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" /> <script type="text/javascript"> </script> </head> <body> <div class="row-fluid"> <div class="span6 well"> <h3>upload_file</h3> <input type="file" name="file" /> </div> </div> </body> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> </html>
python代碼
#coding=utf-8 from selenium import webdriver import os,time driver = webdriver.Firefox() #打開上傳文件頁面 file_path = 'file:///' + os.path.abspath('upload_file.html') driver.get(file_path) #定位上傳按鈕,添加本地文件 driver.find_element_by_name("file").send_keys('D:\\selenium_use_case\upload _file.txt') time.sleep(2) driver.quit()