WEB自动化-文件单上传

先看下文件上传是类型是否INPUT框,如果是的话,可以通过send_keys输入,如果不是,需要用鼠标进行操作

INPUT框类型的文件上传:

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

"""
https://layui.dev/docs/2.8/upload/#demo-files-table
"""

driver = webdriver.Chrome()
# 演示用
sleep(5)
# 地址在外网,可能打不开,打不开就打开本地的
# driver.get("https://the-internet.herokuapp.com/upload")
driver.get("file:///C:/Users/gezirui/PycharmProjects/web1/class_07/Upload_Tec/p01_input/upload.html")
time.sleep(2)
driver.find_element(By.ID, "file-upload").send_keys(
    r"C:/Users/gezirui/Desktop/TEST.txt")
sleep(3)
driver.find_element(By.ID, "file-submit").submit()

sleep(5)
# 获取网页源码
content = driver.page_source
print(content)

# 在源码中找关键字
if driver.page_source.find("File Uploaded!") != -1:
    print("file upload success")
else:
    print("file upload not success")

非INPUT框:

这种情况需要借助页面 鼠标操作(屏幕鼠标),需要安装包:

pip install  pyautogui,如果安装报错,试试加上清华大学的镜像源,

pip install  pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple

如果还报错,先安装:pip install pygetwindow -i https://pypi.tuna.tsinghua.edu.cn/simple

代码示例如下:

import pyautogui
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from time import sleep

driver = webdriver.Chrome()
driver.implicitly_wait(10)
# driver.get("https://the-internet.herokuapp.com/upload")
driver.get("file:///Volumes/attached/huace_edu/vipCourse/WebUI_automation/web_source_code/class_07/Upload_Tec/p01_input/upload.html")
# 移动窗口

# 获取元素的坐标
# locator = driver.find_element(By.ID, "file-submit")
# print(locator.rect)

driver.set_window_position(2073, 11) # 点击上传按钮,让它弹框 el = driver.find_element(By.XPATH, "//input") # 使用click报错:InvalidArgumentException: Message: invalid argumen # el.click() # 点击上传 ActionChains(driver).click(el).perform() # 移动到,地址栏,需要先定位 pyautogui.moveTo(3360, 78) sleep(2) # 点击 pyautogui.click() # 删掉原来的路径 pyautogui.press('backspace') # 键盘输入,文件存储的地址 pyautogui.write( r"/Volumes/attached/huace_edu/vipCourse/WebUI_automation/web_new_code/class_07/") # 按enter,这里要按2下才生效 pyautogui.press('enter') pyautogui.press('enter') # 移动鼠标 pyautogui.moveTo(3406, 255) # 点击上传文件 pyautogui.click() # 移动鼠标 pyautogui.moveTo(3804, 614) # 点击,打开按钮 pyautogui.click() # 点击网页中的upload driver.find_element(By.ID, "file-submit").submit() # 获取网页源码 content = driver.page_source print(content) # 在源码中找关键字 if (driver.page_source.find("File Uploaded!")): print("file upload success") else: print("file upload not success")

 

posted @ 2023-07-28 01:58  琉璃星眸  阅读(27)  评论(0编辑  收藏  举报