selenium WebDriver 自动化测试之文件上传及弹框alert处理

文件上传

input标签可直接使用send_keys(文件地址)上传文件

self.driver.find_element_by_id('上传按钮id').send_keys('文件路径+文件名')

下面以百度图片搜索上传图片为例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:base.py
@time:2020/10/17
"""
import os

from selenium import webdriver


class Base:
    def setup_class(self):
        # option = webdriver.ChromeOptions()
        # option.add_experimental_option('w3c', False)
        # self.driver = webdriver.Chrome(options=option)
        browser = os.getenv('browser')
        if browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'headless':
            self.driver = webdriver.phantomjs()
        else:
            self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)

    def teardown_class(self):
        self.driver.quit()
View Code

上面代码为演示代码中from test_selenium.base import Base 导入的代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_fileupload.py
@time:2020/10/18
"""
from time import sleep
from test_selenium.base import Base


class TestFileUpload(Base):
    def test_file_upload(self):
        self.driver.get('https://image.baidu.com/')
        self.driver.find_element_by_xpath('//*[@id="sttb"]/img[1]').click()
        sleep(2)
        self.driver.find_element_by_id('stfile').send_keys('/Users/chenshifeng/Desktop/photo.png')
        sleep(5)

弹框处理机制

在页面操作中有时会遇到JavaScript所生产的alert,confirm,以及prompt弹框,可以使用switch_to.alert()方法定位到,然后使用text/accept/dismiss/send_keys等方法进行操作

操作alert常用方法

  • switch_to.alert():获取当前页面上的警告框
  • text:返回alert/confirm/prompt中的文字信息
  • accept():接受现有警告框
  • dismiss():解散现有警告框
  • send_keys(KeysToSend):发送文本至警告框

举例说明:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_alert.py
@time:2020/10/18
"""
from time import sleep
from selenium.webdriver import ActionChains
from test_selenium.base import Base

class TestAlert(Base):
    def test_alert(self):
        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()
        sleep(2)
        self.driver.switch_to.alert.accept()    # 接受警告框
        self.driver.switch_to.default_content()
        self.driver.find_element_by_id('submitBTN').click()
        sleep(2)

end

 

posted @ 2020-10-18 10:55  尘世风  阅读(555)  评论(0编辑  收藏  举报
*/