今天以一個表單的自動提交,來進一步學習selenium的用法css
練習目標html
0)運用selenium啓動firefox並載入指定頁面(這部分可查看本人文章 http://www.cnblogs.com/liu2008hz/p/6958126.html)python
1)頁面元素查找(多種查找方式:find_element_*)web
2)內容填充(send_keys)瀏覽器
3)iframe與父頁面切換(switch_to_frame是切換到iframe,switch_to_default_content是切換到主頁面)學習
4)瀏覽器交互處理:window.alert, window.confirm, window.prompt測試
與上面的三個瀏覽器交互內容,須要用到switch_to_alert,有幾個用法須要注意:spa
a)accept():發送肯定指令,至關於點擊「肯定」按鈕firefox
b)dismiss():取消操做,至關於點擊「取消」按鈕或點擊右上角「關閉」orm
c)send_keys:填充prompt框須要填寫的內容
準備工做
html頁面(註冊頁,內嵌一個註冊表單;之因此這樣舉例,是爲了介紹練習selenium的switch_to_frame的用法)
1)註冊頁面(路徑D:\RegisterDEMO\index.htm)
<!DOCTYPE> <html> <head> <title>用戶註冊</title> <meta charset="utf-8" /> </head> <body> <h3>測試Python selenium自動提交表單</h3> <iframe id="register_iframe" width="320" height="200" border="0" src="register.htm" /> </body> </html>
2)註冊表單(路徑D:\RegisterDEMO\register.htm)
<!DOCTYPE> <html> <head> <title>這是內嵌表單</title> <meta charset="utf-8" /> <style type="text/css"> input[type='text']{border:1px solid #abc; font-size:14px; padding:5px; width:200px;} input[type='password']{border:1px solid #abc; font-size:14px; padding:5px; width:200px;} input[type='submit']{border:1px solid #abc; font-size:14px; padding:5px 10px; width:100px; cursor:pointer; margin-top:20px;} input[type='submit']:hover{background-color:#aaaaff;} </style> </head> <body> <form action="/register/regaction" method="POST"> <table> <tr> <td>用戶名:</td> <td><input id="txt_account" type="text" value="" placeholder="用戶名" /></td> </tr> <tr> <td>密碼:</td> <td><input id="txt_password" type="password" value="" placeholder="密碼" /></td> </tr> <tr> <td>電子郵箱:</td> <td><input id="txt_email" type="text" value="" placeholder="電子郵箱" /></td> </tr> <tr> <td> </td> <td><input id="btn_register" type="submit" value="提交註冊" onclick="return confirm('是否確認提交註冊');" /></td> </tr> </table> </form> </body> </html>
運行步驟
咱們經過Python IDLE一步步來運行,這有助於理解,一步一個操做,驚喜不斷
1)引入selenium模塊
from selenium import webdriver
2)啓動firefox並載入註冊頁面
bs = webdriver.Firefox() bs.get('file:///D:/RegisterDEMO/index.htm')
3)查找輸入框(用戶名、密碼、電子郵件)和按鈕(提交註冊),並填充指定內容
# 因爲表單內容是嵌在iframe裏的,因此須要查找指向至iframe # 若是又想跳出iframe,回到父頁面,能夠使用 bs.switch_to_default_content() bs.switch_to_frame('register-iframe') # 因爲全部的元素都命名了id,能夠使用find_element_by_id,還有不少的其它find_element_*你們能夠練習 # 查找用戶名框,並填充「hertz.liu" account = bs.find_element_by_id('txt_account') account.send_keys('hertz.liu') # 查找密碼框,並填充"pwd123" pwd = bs.find_element_by_id('txt_password') pwd.send_keys('pwd123') # 查找電子郵箱框,並填充」hertz.liu@mail.com" email = bs.find_element_by_id('txt_email') email.send_keys('hertz.liu@mail.com') # 查找提交按鈕,並模擬點擊提交 btn_reg = bs.find_element_by_id('btn_register') btn_reg.click()
4)很是順利的,完成了表單的填充和提交。通常的表單,因爲涉及到數據的操做,開發人員都會設置一些二次確認以防止誤操做。此處就是用了簡單的confirm來進行二次確認,下面是如何讓selenium來識別出confirm框,並點擊「肯定」按鈕
# 將查找對象轉移至confirm confirm = bs.switch_to_alert() # 點擊肯定按鈕 confirm.accept() # 若是要取消,使用confirm.dismiss() # 若是是prompt,則能夠使用send_keys()先填充內容,再調用accept()或dismiss()
5)關閉瀏覽器
bs.close()