文件上傳
-
input標(biāo)簽可以直接使用
send_key(文件地址)
上傳文件 - 用法:
el = driver.find_element_by_id('上傳按鈕id')
el.send_keys("文件路徑+文件名")
- 案例
- 打開百度圖片首頁:https://image.baidu.com/
- 點(diǎn)擊
攝像機(jī)
按鈕 - 點(diǎn)擊
選擇文件
按鈕 -
選擇本地文件上傳
image.png
image.png - 案例代碼:
from time import sleep
from selenium import webdriver
class TestFile:
def setup(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(5)
def teardown(self):
self.driver.quit()
def test_file_upload(self):
self.driver.get("https://image.baidu.com/")
self.driver.find_element_by_id("sttb").click()
self.driver.find_element_by_id("uploadImg").send_keys("1.png")
sleep(2)
彈框處理機(jī)制
- 在頁面操作中有時(shí)會(huì)遇到JavaScript所生成的alert赃泡、confirm以及prompt彈框,可以使用
switch_to.alert()
方法定位到鞋真。然后使用 text/ accept / dismiss / send_keys等方法進(jìn)行操作崇堰。 - 操作alert常用的方法:
-
switch_to.alert()
:獲取當(dāng)前頁面上的警告框。 -
text
:返回alert / confirm / prompt中的文字信息涩咖。 -
accept()
:接受現(xiàn)有警告框海诲。 -
dismiss()
:解散現(xiàn)有警告框。 -
send_keys(keysToSend)
:發(fā)送文本至警告框抠藕。keysToSend
:將文本發(fā)送至警告框饿肺。
-
模擬彈框
- 在Console里輸入
window.alert("這是一個(gè)彈框")
image.png
alert窗口處理案例
- 測試案例:
- 打開網(wǎng)頁:https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable
- 操作窗口頁面 將元素1拖拽到元素2這時(shí)候會(huì)有一個(gè)alert彈框,點(diǎn)擊彈框中的’確定’
- 然后再按'點(diǎn)擊運(yùn)行'
- 關(guān)閉網(wǎng)頁
image.png
image.png
- 實(shí)例代碼:
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
class TestAlert:
def setup(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(5)
def teardown(self):
self.driver.quit()
def test_alert(self):
self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
self.driver.switch_to.frame("iframeResult") # 切換到iframe中
drag = self.driver.find_element_by_id("draggable")
drop = self.driver.find_element_by_id("droppable")
action = ActionChains(self.driver)
action.drag_and_drop(drag, drop).perform() # 將元素1拖拽到元素2
sleep(2)
alert = self.driver.switch_to.alert
print(alert.text) # 打印彈窗信息
alert.accept() # 點(diǎn)擊彈框的確定
self.driver.switch_to.default_content() # 切換到默認(rèn)frame中
self.driver.find_element_by_id("submitBTN").click()
下一節(jié):Page Object設(shè)計(jì)模式盾似,Page Object模式的發(fā)展歷史介紹敬辣。