第一种:
通过元素的input属性:
driver = webdriver.Chrome()
driver.get('https://www.layui.com/demo/upload.html')
# 方式一:找到对应的input标签,直接使用send_keys输入文件路径
input_ele = driver.find_elements_by_xpath('//button[@id="test1"]/../input')
input_ele.send_keys(r'C:\images\1.gif')
如果找不到上传文件元素的input标签:
解决方案一:PC端自动化的库:
1、pywinauto
- 优点:可以识别带有中文的路径
- 缺点:只能在windows下面使用,安装的时候也会有点问题,和python部分版本不兼容
pip install pywinauto
①单文件上传:
from pywinauto,keyboard import send_keys
send_keys(r'C:\images\1.gif')
send_keys("{VK_RETURN}")
②多文件上传
from pywinauto,keyboard import send_keys
driver.find_element_by_xpath('//button[@id="test2"]').click()
time.sleep(2)
send_keys(r'"C:\images\1.gif"')
send_keys(r'"C:\images\2.gif"')
send_keys("{VK_RETURN}")
2、pyautogui
- 优点:mac、linux、windows都可适用
- 缺点:上传路径不能带中文
import pyautogui
driver.find_element_by_xpath('//button[@id="test2"]').click()
time.sleep(2)
pyautogui.write('d:\images\1.gif')
pyautogui.press('enter', 2)
上传文件封装:
def upload_file(*args):
time.sleep(2)
for path in args:
send_keys('"{}"'.format(path))
send_keys("{VK_RETURN}")
def work2():
driver = webdriver.Chrome()
driver.get('https://www.layui.com/demo/upload.html')
driver.find_elements_by_xpath('//button[@id="test2"]')
upload_file(r'C:\images\1.gif')
time.sleep(3)