1. 程式人生 > >python3 + selenium 之檔案上傳下載

python3 + selenium 之檔案上傳下載

檔案上傳

檔案上傳下載的聯絡html:

uplad.html

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>upload_file</title>
<link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />
</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://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script> </html>

開啟上面的html長這樣:

點選後:

方法一

如頁面的的元素標籤是input如下下圖:

可直接賦值send_keys輸入

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("file:///C:/Users/WeiBing/Desktop/uplad.html")
aaa =driver.find_element_by_xpath("//*[@name='file']")
aaa.send_keys("D:/a.txt")//直接將檔案輸入
time.sleep(5)
driver.quit()

方法二

使用AutoIt來完成

下載AutoIt 下載安裝完成後點選開始選單可看到如下選單

AutoIt Windows Info 用於幫助我們識Windows控制元件資訊。 Compile Script to.exe 用於將AutoIt生成 exe 執行檔案。 Run Script 用於執行AutoIt指令碼。 SciTE Script Editor 用於編寫AutoIt指令碼。

1、首先開啟AutoIt Windows Info 工具,滑鼠點選Finder Tool,滑鼠將變成一個小風扇形狀的圖示,按住滑鼠左鍵拖動到需要識別的控制元件上。 開啟後介面如下:

識別輸入框控制元件

識別開啟按鈕

通過AutoIt Windows Info 獲得以下資訊。 視窗的title為“選擇要載入的檔案”,標題的Class為“#32770”。 檔名輸入框的class 為“Edit”,Instance為“1” ,所以ClassnameNN為“Edit1”。 開啟按鈕的class 為“Button”,Instance為“1” ,所以ClassnameNN為“Button1”。

2、 根據AutoIt Windows Info 所識別到的控制元件資訊開啟SciTE Script Editor編輯器,編寫指令碼。

ControlFocus("開啟","","Edit1") 
WinWait("[CLASS:#32770]","",10)  
ControlSetText("開啟","","Edit1", $CmdLine[1]) # $CmdLine[1]是命令列引數用於接收需要上傳的檔案,跟指令碼中的 os.system('D:\\AA.exe D:\\a.txt')對應
Sleep(2000) 
ControlClick("開啟","","Button1");#如果是下載我們可以找到按鈕直接點選

或這樣:

ControlFocus("開啟","","Edit1")
WinWait("[CLASS:#32770]","",10)
ControlSetText("開啟","","Edit1","D:\a.txt")
Sleep(2000)#毫秒
ControlClick("開啟","","Button1");

ontrolFocus()方法用於識別Window視窗。WinWait()設定10秒鐘用於等待視窗的顯示,其用法與WebDriver 所提供的implicitly_wait()類似。ControlSetText()用於向“檔名”輸入框內輸入本地檔案的路徑。這裡的Sleep()方法與Python中time模組提供的Sleep()方法用法一樣,不過它是以毫秒為單位,Sleep(2000)表示固定休眠2000毫秒。ControlClick()用於點選上傳視窗中的“開啟”按鈕。   AutoIt的指令碼已經寫好了,儲存通過選單欄“Tools”–>“Go” (或按鍵盤F5)來執行一個指令碼吧!注意在執行時如下視窗處於開啟狀態。   

3、指令碼執行正常,儲存到本地AA.au3,這裡儲存的指令碼可以通過Run Script 工具將其開啟執行,但我們的目的是希望這個指令碼被Python程式呼叫,那麼就需要將其生成exe程式。開啟Compile Script to.exe工具,將其生成為exe可執行檔案。

點選“Browse”選擇upfile.au3檔案,點選“Convert”按鈕將其生成為AA.exe程式。

程式碼示例

from selenium import webdriver 
import os import time 
driver = webdriver.Chrome() driver.get("file:///C:/Users/WeiBing/Desktop/uplad.html") 
driver.find_element_by_xpath("//*[@name='file']").click() #點選上傳按鈕,會彈出上傳框 
os.system('D:\\AA.exe D:\\a.txt') #執行前面生成的exe檔案,D:\\a.txt上傳 
time.sleep(5) 
driver.quit()

成功

檔案下載

參考連結 也可以使用上面上傳使用的autoit工具