Python selenium browser upload file operation (recommended method two)

Method 1: This method is only suitable for a single browser to run, to ensure that the keyboard operation does not lose focus and cannot be performed concurrently

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys
import time
import unittest
import traceback
import win32clipboard as w
import win32api
import win32con
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException,NoSuchElementException

def setText(aString): #给剪切板写内容
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(win32con.CF_UNICODETEXT,aString)
    w.CloseClipboard()

VK_CODE={
    
     #键盘按键对应操作系统的16位表示
    'enter':0x0D,
    'ctrl':0x11,
    'v':0x56
    }

def keyDown(keyName):
    win32api.keybd_event(VK_CODE[keyName],0,0,0)

def keyUp(keyName):
    win32api.keybd_event(VK_CODE[keyName],0,win32con.KEYEVENTF_KEYUP,0)

driver=webdriver.Chrome()
url='https://fanyi.baidu.com/?aldtype=16047#auto/zh'
driver.get(url)
time.sleep(3)
wait=WebDriverWait(driver,10,0.2)
wait.until(EC.element_to_be_clickable((By.ID,'upload-btn'))) #等待元素出现
setText("e:\\a.txt") #给剪切板写入文件路径
driver.find_element_by_xpath("//div[@id='upload-btn']").click() #点击元素
time.sleep(2)
keyDown('ctrl') #将剪切板内容粘贴在弹框中
keyDown('v')
time.sleep(2)
keyUp('v')
keyUp('ctrl')
time.sleep(2)
keyDown('enter') #按回车
keyUp('enter')
time.sleep(3)
fileSubmitButton=driver.find_element_by_id('filesubmit')
fileSubmitButton.click() #点击提交按钮

Method Two

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys
import time
import unittest
import traceback
import win32clipboard as w
import win32api
import win32con
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException,NoSuchElementException

driver=webdriver.Ie()
url='http://127.0.0.1/test_upload_file.html'
driver.get(url)
time.sleep(3)
wait=WebDriverWait(driver,10,0.2)
wait.until(EC.element_to_be_clickable((By.ID,'file'))) #等待元素出现
driver.find_element_by_xpath("//input[@id='file']").send_keys('e:\\a.txt') #定位元素并输入路径
time.sleep(2)
fileSubmitButton=driver.find_element_by_id('filesubmit')
fileSubmitButton.click() #点击提交按钮

Guess you like

Origin blog.csdn.net/weixin_44123630/article/details/113839098