python+webdriver+autoit實現百度雲盤檔案上傳
阿新 • • 發佈:2019-02-06
web上傳檔案的功能一般有兩種方式:
1. 普通上傳:將本地檔案的路徑作為一個值放在input標籤中,通過form表單將這個值提交給伺服器
2. 外掛上傳:一般指基於Flash,Javascript,或者Ajax等技術實現的上傳功能
下面舉例說明自動化百度雲盤的上傳功能:
1.分析頁面:
實現步驟:
1. 登入頁面
2. 找到上傳控制元件
3. 在開啟的上傳檔案的視窗中選中要上傳的檔案
2.登入頁面的元素:
可以確定其xpath為:
/html/body/div[1]/div[1]/div[2]/div[3]/div[2]/form/p[5]/input
使用同樣的方法,找到密碼和“登入”按鈕的xpath
driver = webdriver.Firefox()
driver.get("http://wangpan.baidu.com//")
#登入
driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[2]/div[3]/div[2]/form/p[5]/input').send_keys('使用者名稱')
driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[2]/div[3]/div[2]/form/p[6]/input').send_keys('密碼')
driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[2]/div[3]/div[2]/form/p[9]/input' ).click()
3.登入成功之後,點選上傳,彈出檔案上傳視窗
找到其xpath:
/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[2]/a[1]/form/input
程式碼:
#點選上傳,開啟上傳檔案視窗
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[2]/a[1]/form/input').click()
滑鼠單擊“上傳”,彈出檔案上傳視窗:
4.上傳檔案
webdriver無法對windows的圖形介面進行操作,所以藉助AutoIt來實現檔案上傳。
AutoIt下載: https://www.autoitscript.com/site
4.1使用AutoIt識別windows控制元件
安裝AutoIt之後,開啟AutoIt Window Info(x64)
4.2 然後獲取檔案上傳視窗的控制元件資訊:
開啟autoit工具之後,用滑鼠將Finder Tool的圖示拖到要識別的控制元件上
- 獲取文字框的控制元件資訊:
- 獲取“開啟”按鈕的控制元件資訊:
4.3編寫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指令碼呼叫
4.4使用python指令碼呼叫AutoIt指令碼
#點選上傳,開啟上傳檔案視窗
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[2]/a[1]/form/input').click()
#使用autoit指令碼自動上傳檔案
#需要匯入python的os庫檔案: import os
os.system("D:/upfile.exe")