Foreplay
In the process of web automation, the function of uploading files is often needed. selenium can upload files by using send_keys(), but there are great limitations in using send_keys(). Only input tags can be uploaded, and many tags can't be uploaded. Here we use the third-party module pywin32 to simulate uploading files.
actual combat
Create a file of win32Model.py, write the following code
import win32clipboard as w import win32con class Clipboard(object): #simulation windows Set clipboard #Read clipboard @staticmethod def getText(): #Open clipboard w.OpenClipboard() #Get data from clipboard d=w.GetClipboardData(win32con.CF_TEXT) #Close clipboard w.CloseClipboard() #Return clipboard data to caller return d #Set clipboard contents @staticmethod def setText(aString): #Open clipboard w.OpenClipboard() #clear clipboard w.EmptyClipboard() #Will data aString Write to clipboard w.SetClipboardData(win32con.CF_UNICODETEXT,aString) #Close clipboard w.CloseClipboard()
After creating a win32Key.py file, write the following code
import win32api import win32con class KeyboardKeys(object): #Analog keyboard key class VK_CODE={ 'enter':0x0D, 'ctrl':0x11, 'v':0x56 } @staticmethod def keyDown(keyName): #Press button win32api.keybd_event(KeyboardKeys.VK_CODE[keyName],0,0,0) @staticmethod def keyUp(keyName): #Release key win32api.keybd_event(KeyboardKeys.VK_CODE[keyName],0,win32con.KEYEVENTF_KEYUP,0) @staticmethod def oneKey(key): #Simulate a single key KeyboardKeys.keyDown(key) KeyboardKeys.keyUp(key) @staticmethod def twoKeys(key1,key2): #Simulate two key combinations KeyboardKeys.keyDown(key1) KeyboardKeys.keyDown(key2) KeyboardKeys.keyUp(key2) KeyboardKeys.keyUp(key1)
Write master function
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') # Simulated carriage return 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)