python-UI文件上傳

我們在使用python做web自動化的過程中,經(jīng)常會遇到文件上傳的操作。對于文件上傳存在input輸入框情況,可以直接定位input元素,使用send_keys(filepath)方法實(shí)現(xiàn)。對于沒有input輸入框的文件上傳,則需要借助第三方工具,在上傳文件時(shí)打開系統(tǒng)窗口。以下是兩個(gè)上傳文件操作比較簡單的工具

  • windows系統(tǒng):pywinauto庫

    安裝:pip install pywinauto
    導(dǎo)入:from pywinauto.keyboard import send_keys
  • mac/Linux/window通用:pyautogui 跨平臺

    python3.8環(huán)境:先安裝依賴 pip install pillow==6.2.2,再安裝 pip install pyautogui
    非python3.8環(huán)境:直接 pip install pyautogui
    導(dǎo)入:import pyautogui

1,input元素使用send_keys()方法

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.implicitly_wait(10)
URL = 'https://xxxx/kk-form/fs/fm/form/161519068236342881d3774ec5428571/fill'
driver.get(URL)
# 獲取上傳組件的元素
f = driver.find_element('xpath', "(//input[@class='van-uploader__input'])[1]")
# 使用send_keys直接發(fā)送文件路徑即可
f.send_keys(r'/Users/lili/Documents/weixin.jpeg')
time.sleep(5)
driver.quit()

2,非input元素,window方法:使用pywinauto庫

import pyautogui as pyautogui
from pywinauto.keyboard import send_keys
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.implicitly_wait(10)
URL = 'https://xxxx/kk-form/fs/fm/form/161519068236342881d3774ec5428571/fill'
driver.get(URL)
f = driver.find_element('xpath', "(//input[@class='van-uploader__input'])[1]")
# 觸發(fā)點(diǎn)擊事件,讓系統(tǒng)的彈框彈出來
f.click()
# 等待,因?yàn)閺椏驈棾鰜硇枰獣r(shí)間
time.sleep(1)
# 這里是pywinauto 的send_keys 方法
send_keys(r'/Users/lili/Documents/weixin.jpeg')
# 使用return提交
send_keys('{VK_RETURN}')

3,非input元素,mac/Linux/window的通用方法:pyautogui庫

from selenium import webdriver
import pyautogui
import time

driver = webdriver.Chrome()
driver.implicitly_wait(10)
URL = 'https://xxxx/kk-form/fs/fm/form/161519068236342881d3774ec5428571/fill'
driver.get(URL)
f = driver.find_element('xpath', "(//input[@class='van-uploader__input'])[1]")
# 觸發(fā)點(diǎn)擊事件,讓系統(tǒng)的彈框彈出來
f.click()
time.sleep(1)
# 寫入路徑
pyautogui.write(r'/Users/lili/Documents/weixin.jpeg')
# 敲回車:相當(dāng)于點(diǎn)擊【打開】按鈕,需要敲2次,避免失敗
pyautogui.press('enter', 2)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容