環境準備
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路徑

代碼:
#選擇賬號密碼登錄driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[6]/div[2]/a').click()# 登錄 driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[5]/input').send_keys('username')driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[6]/input').send_keys('password')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"]
代碼:
#上傳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腳本,實現文件上傳
1.打開scite script editor
2.代碼:
;ControlFocus("title", "text", controlID) Edit1=Edit instance 1ControlFocus("文件上傳", "","Edit1");Wait 10 seconds for the Upload window to appearWinWait("[CLASS:#32770]", "",10);Set the File name thext on the Edit fieldControlSetText("文件上傳", "", "Edit1", "D:/test.txt")Sleep(2000);Click on the Open buttonControlClick("文件上傳", "", "Button1");3. 將文件保存upfile.au3

4. 使用compile script to exe將上述AutoIt腳本編譯為exe文件供python腳本調用

6、最后,使用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 osos.system("D:/upfile.exe")完整代碼如下:
import osfrom selenium import webdriverimport timeclass Connect(): def __init__(self,UserName,PassWord,URL): self.UserName = UserName self.PassWord = PassWord self.URL = URL def connect(self): self.driver = webdriver.Firefox() self.driver.get(self.URL) self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[6]/div[2]/a').click() 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) 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) self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[6]/div/div[3]/form/p[9]/input').click() #設置思考時間 time.sleep(30) sreach_window = self.driver.current_window_handle # 此行代碼用來定位當前頁面 self.driver.find_element_by_xpath('//*[@id="h5Input0"]').click() os.system(r"C:/Users/zg/Desktop/upfile.exe")Connect(UserName,PassWord,URL).upload()以上這篇Python實現對百度云的文件上傳(實例講解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答