selenium之文件上传

文件上传

相信各位再使用自动化的时候,会遇到过上传文件的情况把;今天我们就来了解一下文件上传的几种方式;有selenium自己的,也有其它的工具的使用;但是都是适用于web自动化的;

为什么还需要其它工具,因为你不能确定你的标签,是一个正规的文件上传标签input[type='file'];所以就要用到其它工具

在 Web 应用程序的自动化测试中,文件上传是一个常见且重要的功能。无论是上传用户头像、附件、还是导入数据,确保文件上传功能的稳定性和正确性至关重要。本文将深入探讨 Web 自动化测试中处理文件上传的各种方法,并结合实际例子进行说明。
准备工作
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
class upload_file:
    def __init__(self, path):
        self.path = path
        self.service = Service(path)
        self.driver = webdriver.Chrome(service=self.service)

    def close(self):
        time.sleep(5)
        self.driver.close()

serve_path = r'D:\Code_Study\driver\chromedriver-win64\chromedriver.exe'
upload = upload_file(serve_path)
文件上传标签input[type='file']

当页面上存在一个input[type='file']标签的时候,可以直接和selenium交互

    def input_file(self,filename):
        self.driver.get("https://the-internet.herokuapp.com/upload")
        file_input = self.driver.find_element(By.CSS_SELECTOR, "input[type='file']")
        time.sleep(5)
        # 使用send_keys,把本地文件路径和发送到input元素;
        file_input.send_keys(filename)
        time.sleep(5)
        self.driver.find_element(By.ID, "file-submit").click()
        time.sleep(5)
        file_name_element = self.driver.find_element(By.ID, "uploaded-files")
        file_name = file_name_element.text
        assert file_name == "selenium.png"

# 输出当前文件路径
print(os.path.dirname(__file__))
# 把路径和文件拼接
print(os.path.join(os.path.dirname(__file__), "selenium.png"))
# 获取绝对路径
print(os.path.abspath(
    os.path.join(os.path.dirname(__file__), "selenium.png")))
file_path =os.path.abspath(
    os.path.join(os.path.dirname(__file__), "selenium.png"))
# 上传的时候,建议使用绝对路径
upload.input_file(file_path)
非文件上传标签input[type='file']

并非所有文件上传功能都使用标准的 <input type="file"> 标签。有些 Web 应用会使用自定义的 UI 元素(如按钮、拖拽区域)来触发文件选择和上传。对于这些情况,直接使用 send_keys() 是行不通的。以下是一些常见的处理方法:

  • 直接调用API,就是直接发起请求
  • JS上传;如果文件上传元素是隐藏的,可以使用 JavaScript 使其可见。
  • 使用第三方工具,如果文件上传不是通过 <input type="file"> 实现的,可能需要使用第三方工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值