本文转自测试人社区,原文链接:https://ceshiren.com/t/topic/31691

文件上传的自动化

文件上传

  • input标签可以直接使⽤send_keys(⽂件地址)上传⽂件
  • ⽤法:
  • el = driver.find_element_by_id(‘上传按钮id’)
  • el.send_keys(”⽂件路径+⽂件名")

文件上传实例

测试案例:(这个地方有点小坑,练习时建议用搜狗的网址)
❖ 打开搜狗图⽚⽹址:https://pic.sogou.com/ ❖ 识别上传按钮
❖ 点击上传按钮
❖ 将本地的图⽚⽂件上传

class TestFileUp(base):
    def test_file_upload(self):
        """
        利用input标签可以直接使⽤send_keys(⽂件地址)上传⽂件的特性,进行本地文件上传
        1、访问 https://pic.sogou.com/
        2、访问文件上传界面
        3、用xpath定位到文件上传的input标签处,直接使⽤send_keys(⽂件地址)方式,上传⽂件
        :return:
        """
        self.driver.get("https://pic.sogou.com/")
        self.driver.find_element(By.CLASS_NAME, "camera-ico").click()
        time.sleep(3)
        self.driver.find_element(By.XPATH, "//*[@accept='image/*']").send_keys(r"D:\开发项目\selenium\1.png")
        time.sleep(3)

弹框处理机制 (普通方法没法定位到弹框)

识别弹框

  • alert、confirm和prompt弹框
  • div弹框:

软件测试学习笔记丨Selenium 文件上传、弹框处理_文件上传

操作alert弹框常用的方法:

  • switch_to.alert():获取当前页⾯上的警告框。
  • text:返回alert/confirm/prompt 中的⽂字信息。
  • accept():接受现有警告框(点击"确定"或者"是")
  • dismiss():解散现有警告框(点击"否"或者"取消")
  • send_keys(keysToSend):发送⽂本⾄警告框,keysToSend:将⽂本发送⾄警告框
    拓展地址: https://huilansame.github.io/archivers/switch-to-alert-window-div 实例:
def test_alert(self):
        """
        弹框处理
        1、访问 https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable
        2、操作窗口右侧页面,将元素1拖拽到元素2
        3、点击显示出来的弹框中的"确定"
        4、点击运行
        5、关闭网页
        :return:
        """
        self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
        self.driver.switch_to.frame('iframeResult')

        drag = self.driver.find_element(By.ID, "draggable")
        drop = self.driver.find_element(By.ID, "droppable")
        ActionChains(self.driver).drag_and_drop(drag, drop).perform()
        time.sleep(2)
        print("点击alert 确认")
        self.driver.switch_to.alert.accept()  # 点击弹框中的确认按钮
        self.driver.switch_to.default_content()
        self.driver.find_element(By.ID, "submitBTN").click()
        time.sleep(3)