python selenium浏览器上传文件操作(推荐用方法二)

方法一:该方法只适合单个浏览器运行,保证键盘操作是不丢失焦点,无法做并发

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() #点击提交按钮

方法二

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() #点击提交按钮
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值