前戲
在進行web自動化的時候,經常需要用到上傳文件的功能,selenium可以使用send_keys()來上傳文件,但是使用send_keys()上傳文件有很大的局限性,只能上傳input標簽的,好多的標簽的都上傳不了,我們這里使用第三方模塊pywin32來模擬上傳文件
實戰
創建一個win32Model.py的文件,寫如下代碼
import win32clipboard as w import win32con class Clipboard(object): #模擬windows設置剪貼板 #讀取剪貼板 @staticmethod def getText(): #打開剪貼板 w.OpenClipboard() #獲取剪貼板中的數據 d=w.GetClipboardData(win32con.CF_TEXT) #關閉剪貼板 w.CloseClipboard() #返回剪貼板數據給調用者 return d #設置剪貼板內容 @staticmethod def setText(aString): #打開剪貼板 w.OpenClipboard() #清空剪貼板 w.EmptyClipboard() #將數據aString寫入剪貼板 w.SetClipboardData(win32con.CF_UNICODETEXT,aString) #關閉剪貼板 w.CloseClipboard()
在創建一個win32Key.py文件,寫如下代碼
import win32api import win32con class KeyboardKeys(object): #模擬鍵盤按鍵類 VK_CODE={ 'enter':0x0D, 'ctrl':0x11, 'v':0x56 } @staticmethod def keyDown(keyName): #按下按鍵 win32api.keybd_event(KeyboardKeys.VK_CODE[keyName],0,0,0) @staticmethod def keyUp(keyName): #釋放按鍵 win32api.keybd_event(KeyboardKeys.VK_CODE[keyName],0,win32con.KEYEVENTF_KEYUP,0) @staticmethod def oneKey(key): #模擬單個按鍵 KeyboardKeys.keyDown(key) KeyboardKeys.keyUp(key) @staticmethod def twoKeys(key1,key2): #模擬兩個組合鍵 KeyboardKeys.keyDown(key1) KeyboardKeys.keyDown(key2) KeyboardKeys.keyUp(key2) KeyboardKeys.keyUp(key1)
寫主函數
from selenium import webdriver from time import sleep from page.win32Model import Clipboard from page.win32Key import KeyboardKeys def upload(path): Clipboard.setText(path) sleep(1) KeyboardKeys.twoKeys('ctrl','v') KeyboardKeys.oneKey('enter') # 模擬回車 driver = webdriver.Chrome() driver.get('xxx') driver.find_element_by_class_name('el-button').click() driver.maximize_window() sleep(2) driver.find_element_by_xpath('xxx').click() upload(r'C:\Users\Administrator\Desktop\21.png') sleep(2)