環境准備
python3.6
PyCharm 2017.1.3
Windows環境
框架搭建
selenium3.6
安裝方法:
pip install selenium
實現步驟:
一、步驟分析
1、選擇“賬號密碼登錄”
2、用戶名、密碼輸入,登錄
3、文件上傳
注:本文主要介紹利用selenium包下的webdriver加載Firefox瀏覽器。
二、元素捕捉
利用火狐瀏覽器firebug插件復制控件的XPATH路徑,注:Python3.6對應Firefox版本40.x,暫不支持最新版本50.x。
1、點擊“賬號密碼登錄”,獲取其源文件
效果圖如下:
點擊右鍵,復制Xpath路徑:/html/body/div[1]/div[3]/div[6]/div/div[6]/div[2]/a
登錄按鈕和文件上傳同上,獲取其相應的Xpath路徑
代碼:
1 #選擇賬號密碼登錄 2 driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[6]/div[2]/a').click() 3 # 登錄 4 driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[5]/input').send_keys('username') 5 driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[6]/input').send_keys('password') 6 driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[9]/input').click()
2、登錄成功后,點擊文件上傳,彈出文件對話框
“上傳”的Xpath路徑為://*[@id="h5Input0"]
代碼:
1 #上傳 2 driver.find_element_by_xpath('//*[@id="h5Input0"]').click()
點擊上傳按鈕,彈出文件對話框
三、AutoIT編寫腳本實現上傳文件
webdriver無法對文件直接進行操作,所以需要借助AutoIT來實現文件上傳
AutoIT下載地址:https://www.autoitscript.com/site
安裝AutoIt之后,打開AutoIt Window Info(x64)
4、獲取文件上傳窗口的控件信息:
打開autoit工具之后,用鼠標將Finder Tool的圖標拖到要識別的控件上
- 獲取文本框的控件信息:
- 獲取“打開”按鈕的控件信息:
5、編寫AutoIt腳本,實現文件上傳
- 打開scite script editor
- 代碼:
;ControlFocus("title", "text", controlID) Edit1=Edit instance 1 ControlFocus("文件上傳", "","Edit1") ;Wait 10 seconds for the Upload window to appear WinWait("[CLASS:#32770]", "",10) ;Set the File name thext on the Edit field ControlSetText("文件上傳", "", "Edit1", "D:\test.txt") Sleep(2000) ;Click on the Open button ControlClick("文件上傳", "", "Button1");
3. 將文件保存upfile.au3
4. 使用compile script to exe將上述AutoIt腳本編譯為exe文件供python腳本調用
6、最后,使用Python腳本調用AutoIT腳本
1 #點擊上傳,打開上傳文件窗口 2 driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[2]/a[1]/form/input').click() 3 4 #使用autoit腳本自動上傳文件 5 #需要導入python的os庫文件: import os 6 os.system("D:/upfile.exe")
完整代碼如下:

1 import os 2 from selenium import webdriver 3 import time 4 class Connect(): 5 def __init__(self,UserName,PassWord,URL): 6 self.UserName = UserName 7 self.PassWord = PassWord 8 self.URL = URL 9 def connect(self): 10 self.driver = webdriver.Firefox() 11 self.driver.get(self.URL) 12 self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[6]/div[2]/a').click() 13 self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[5]/input').send_keys(self.UserName) 14 self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[6]/input').send_keys(self.PassWord) 15 self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[9]/input').click() 16 #設置思考時間 17 time.sleep(30) 18 sreach_window = self.driver.current_window_handle # 此行代碼用來定位當前頁面 19 self.driver.find_element_by_xpath('//*[@id="h5Input0"]').click() 20 os.system(r"C:\Users\zg\Desktop\upfile.exe") 21 Connect(UserName,PassWord,URL).upload()
本文參考文章:http://blog.csdn.net/justheretobe/article/details/50939021