selenium WebDriver 自動化測試之檔案上傳及彈框alert處理
阿新 • • 發佈:2020-10-18
檔案上傳
input標籤可直接使用send_keys(檔案地址)上傳檔案
self.driver.find_element_by_id('上傳按鈕id').send_keys('檔案路徑+檔名')
下面以百度圖片搜尋上傳圖片為例
#!/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 importActionChains 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