selenium+webdriver 實現上傳文件,方法有三種,


今天遇到了自動化ui頁面需要上傳文件的問題,之前有用type="file"類型的input元素進行查找,

今天發現在頁面上無法找個input,他被隱藏在了div下,就導致之前的上傳文件方法用不了了,

針對這個,自己單獨記錄一下

方法一,當input類型是type="file"類型時,可以直接使用

driver.find_element_by_xpath('//*[@class="soutu-btn"]').sendkeys('c:\\user\pc\desktop\00.png')

  這個可以直接講本地的文件上傳。

情況二,當input類型是type=“file”類型,但是在一個button下面時,要是定位這個按鈕是無法上傳的,定位這個input回報錯依然無法上傳,那就需要使用

 

input = driver.find_element_by_xpath('//*[@class="ant-upload"]/input')
input.sendkeys('c:\\user\\pc\\desktop\\00.png')

使用這個方法也是可以解決這個問題

情況三,存在其他情況,看到了一個模擬鍵盤操作的方法

具體不講了,看代碼

創建模擬按鍵

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)

創建按鍵事件文件

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()

進行文件上傳

upload.py

from selenium import webdriver
from time import sleep
from win32Model import Clipboard
from win32Key import KeyboardKeys


def upload(path):
    Clipboard.setText(path)
    sleep(1)
    KeyboardKeys.twoKeys('ctrl','v')
    KeyboardKeys.oneKey('enter')  # 模擬回車


driver = webdriver.Chrome()
driver.get('xxxxx')
driver.maximize_window()
driver.find_element_by_xpath('xxxxxxx').click()
sleep(2)
upload(r'xxxxxx')
sleep(2)

替換自己的地址,元素,上傳文件地址,就可以用了。

總之呢,最后這種方法雖然可以解決大部分問題,但是並不是最完美的,在論壇(https://dev.to/razgandeanu/how-to-upload-files-with-selenium-3gj3)上有執行JavaScript進行元素提出的方法,目前還沒有去研究,有興趣的可以進行研究下,

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM