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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM