selenium上傳檔案

2022-05-24 13:33:14 字數 3082 閱讀 8829

1.第一種形式:

input輸入框上傳檔案:可以理解為普通的輸入框輸入,我們只要傳入檔案路徑即可。

普通input框上傳檔案

from selenium import

webdriver

driver =webdriver.chrome()

driver.get(

'')upload = driver.find_element_by_id('

file')

upload.send_keys(r

'c:\users\xibo.zhu\work\myself\myproject\data\picture\test_picture.png

') #

send_keys

print(upload.get_attribute('

value

') ) #

check value

driver.quit()

2.第二種形式非input型上傳:大體上有以下幾種解決方案:

1.autoit,借助外力,我們去呼叫其生成的au3或exe檔案。

2.python pywin32庫,識別對話方塊控制代碼,進而操作

3.sendkeys庫

4.keybd_event,跟3類似,不過是模擬按鍵,ctrl+a,ctrl+c, ctrl+v… 

2.win32gui

1 首先安裝pywin32庫(命令:pip install pywin32)

'''非input輸入框檔案上傳

:param filepath: 上傳檔案的路徑,如果傳多個檔案,檔案路徑格式為 '"d:\\baidu.py" "d:\\upload.py" "d:\\1.html"' 中間用空格隔開

:param multiple: 是否傳遞多個檔案,預設傳乙個檔案

:return:

'''try

:

#win32gui

dialog = win32gui.findwindow('

#32770

', '

檔案上傳

') #

對話方塊 comboboxex32 = win32gui.findwindowex(dialog, 0, '

comboboxex32

', none)

combobox = win32gui.findwindowex(comboboxex32, 0, '

combobox

', none)

edit = win32gui.findwindowex(combobox, 0, '

edit

', none) #

上面三句依次尋找物件,直到找到輸入框edit物件的控制代碼

button = win32gui.findwindowex(dialog, 0, '

button

', none) #

確定按鈕button

if multiple==none:

win32gui.sendmessage(edit, win32con.wm_settext, none, filepath)

#往輸入框輸入絕對位址

win32gui.sendmessage(dialog, win32con.wm_command, 1, button) #

按button

else

: win32gui.sendmessage(edit, win32con.wm_settext, 0, filepath)

#往輸入框輸入絕對位址

win32gui.sendmessage(dialog, win32con.wm_command, 1, button) #

按button

return

true

except

exception as e:

return false

3.# 對於非 input 標籤實現的上傳功能,我們通過模擬鍵盤敲擊的方式實現注意:1:檔案路徑過長的話,可能出現路徑輸入不全。 2:該方法不太穩定。

#

對於非 input 標籤實現的上傳功能,我們通過模擬鍵盤敲擊的方式實現

#觸發檔案上傳的功能

driver.find_element_by_css_selector("

figure.icon

").click()

time.sleep(3)

#模擬鍵盤敲擊,會不管不顧的敲擊,只要**執行到這裡,就敲

sh = win32com.client.dispatch("

wscript.shell")

sh.sendkeys(

"d:\\users\lenovo\pycharmprojects\script\study\seleniumstu\day4\ele.png\r\n")

#注意:**執行過程不要操作滑鼠

#輸入法要保持英文輸入的狀態

Selenium上傳檔案

selenium自帶了對應的api可以上傳問題,如果這個上傳檔案的html code中顯示的type是file那麼你就可以使用下面的 上傳檔案。click the upload button to upload the file this is for hte webfile element the...

selenium 檔案上傳

檔案上傳是web頁面上很常見的乙個功能,自動化成功中操作起來卻不是那麼簡單。一般分兩個場景 一種是input標籤,這種可以用 selenium 提供的send keys 方法輕鬆解決 另外一種非input標籤實現起來比較困難,可以借助 autoit 工具或者 sendkeys 第三方庫。本篇以的上傳...

selenium之檔案上傳

在web頁面中,可能會需要進行或檔案的上傳,但是本地上傳時的對話方塊,是window本身的,無法定位到其元素,那麼 該怎樣進行檔案上傳呢?1 send keys 檔案路徑 開啟檔案上傳對話方塊後,若檔案選擇按鈕是input type file時 對於前端知識,還需要學習後才能繼續補充 通過send ...