前面章節分別介紹了**用WebDriver進行元素定位**,**用WebElement來對元素操作**。本章節對`WebDriver的一些常用方法`進行補充介紹,這一章節的內容也是蠻重要的,希望大家都掌握,否則在實際實戰中,會遇到很多的困擾。
[TOC]
## WebDriver 常用方法
```python
from selenium import webdriver
# 這里會打開一個Chrome瀏覽器空白窗口
driver = webdriver.Chrome()
```
### 在當前瀏覽器session中,加載一個頁面
`get(self, url)`
```python
# 這里瀏覽器會導航到百度首頁
driver.get("www.baidu.com")
```
### 關閉當前頁面
`close(self)`
```python
# 這里會將當期的頁面關閉掉
driver.close()
```
### 隱式等待
`implicitly_wait(self, time_to_wait)`
設置一個固定的超時時間(s),等待一個元素被發現或名字執行完成。在一個session中,只需要設置一次,再整個session有效期內有效。當達到固定的超時時間時,如果元素還沒找到,則會拋出超時異常。如果未達到超時時間,會一直重試。
```python
# 設置全局的元素等待時間30s,如果30s內找到元素,繼續往下執行,如果超過30s都沒有找到元素,則拋出異常。
driver.implicitly_wait(30)
```
### 注銷driver,并且關閉瀏覽器
`quit(self)`
```python
# 這里會將整個瀏覽器都關閉
driver.quit()
```
### 瀏覽器前進
`forward(self)`
```python
# 模擬點擊瀏覽器的“向前-->”
driver.forward()
```
### 瀏覽器后退
`back(self)`
```python
# 模擬點擊瀏覽器的“后退<--"
driver.back()
```
### 刷新當前頁面
`refresh(self)`
```python
# 模擬F5 刷新當前頁面
driver.refresh()
```
### 將當期頁面截圖,保存為png格式
`get_screenshot_as_file(self, filename)`
filename必須要以.png為后綴
```python
# 截圖保存到images/login.png
driver.get_screenshot_as_file("images/login.png")
```
### 在當前會話中添加cookie
`add_cookie(self, cookie_dict)`
參數cookie_dict 是一個字典類型,至少要包含keys:“name”和“value”,可選的key還可以有“path", "domain", "secure", "expiry"
```python
# Go to the correct domain
driver.get("http://www.example.com")
# Now set the cookie. This one's valid for the entire domain
cookie = {'name':'foo', 'value':'bar'}
driver.add_cookie(cookie)
```
### 獲取當前session的全部cookie
`get_cookies(self)`
### 獲取當前session中的指定cookie
`get_cookie(self, name)`
### 刪除當前session中的指定cookie
`delete_cookie(self, name)`
### 刪除當前session中的全部cookie
`delete_all_cookies(self)`
### 在當前頁面中,同步執行JavaScript語句
`execute_script(self, script, *args)`
```python
#在頁面中直接執行js
driver.execute_script('$("#btn1").fadeOut();')
# 直接調用執行js語句
js = "var q=document.getElementById('username');q.style.border='1px solid red';q.value='PTQA TEST' "
driver.execute_script(js)
```
```python
# 在某個已經定位的元素上執行js
button = driver.find_element_by_class_name('btn')
driver.execute_script('$(arguments[0]).click()', button)
```
滾動條滾動舉例:
```python
# 控制div滾動條滾動
js = '$(".modal-body").scrollTop(10000)'
driver.execute_script(js)
```
```python
# 控制瀏覽器的滾動條
js = 'window.scrollTo(0, document.body.scrollHeight);'
driver.execute_script(js)
```
### 在當前頁面中,異步執行JavaScript語句
`execute_async_script(self, script, *args)`
### 設置js超時時間
`set_script_timeout(self, time_to_wait)`
### 設置頁面加載超時時間
`set_page_load_timeout(self, time_to_wait)`
### 窗口最大化
`maximize_window(self)`
### 窗口全屏
`fullscreen_window(self)`
### 窗口最小化
`minimize_window(self)`
### 設置當期窗口大小
`set_window_size(self, width, height, windowHandle='current')`
### 獲取當前窗口大小
`get_window_size(self, windowHandle='current')`
## WebDriver屬性方法
### 返回當前頁面的title
```python
# 獲得當前頁面的title
title = driver.title
```
### 返回當前頁面的url
```python
# 獲得當前頁面的url
url = driver.current_url
```
### 返回當前頁面的源碼
```python
# 獲得當前頁面的源碼
source = driver.page_source
```
### 返回當前窗口的句柄
```python
# 獲得當前窗口的句柄
handle = driver.current_window_handle
```
### 返回當前瀏覽器的所有窗口句柄
```python
# 獲得當前瀏覽器的所有窗口句柄
handles = driver.window_handles
```
### 切換對象(alert,frame,window)
`switch_to`: 返回一個SwitchTo類實例對象。
*切換到彈窗*
`alert = driver.switch_to.alert`
```python
# 切換到當前的彈窗,返回Alert類的一個實例對象
alert = driver.switch_to.alert
# 獲取alert中的文本
alert.text
# 確定
alert.accept()
# 取消、關閉
alert.dismiss()
# 發送文本信息
alert.send_keys(keysToSend)
```
*切換到默認iframe*
`driver.switch_to_default_content()`
*切換到指定iframe*
`driver.switch_to.frame('frame_name')`
`driver.switch_to.frame(1)`
*切換到父iframe*
`driver.switch_to.parent_frame()`
*切換到windows窗口*
`driver.switch_to.window('windowName')`
## 給瀏覽器添加設置項ChromeOptions
```python
options = webdriver.ChromeOptions()
options.add_argument('xxxx')
driver = webdriver.Chrome(chrome_options=options)
```
### 添加瀏覽器 User-Agent
```python
options.add_argument('User-Agent=Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30')
```
### 無界面運行
```python
options.add_argument('--headless')
```
Chrome瀏覽器版本為60以上才支持
<hr style="margin-top:50px">
<section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: 40px 0% 10px;box-sizing: border-box;"><section class="" style="display: inline-block;width: 100%;border-width: 5px;border-style: double;border-color: rgb(23, 22, 24);padding: 10px;border-radius: 2px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="transform: translate3d(20px, 0px, 0px);-webkit-transform: translate3d(20px, 0px, 0px);-moz-transform: translate3d(20px, 0px, 0px);-o-transform: translate3d(20px, 0px, 0px);font-size: 11px;margin: -50px 0% 0px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;width: 7em;height: 7em;display: inline-block;vertical-align: bottom;border-radius: 100%;border-width: 4px;border-style: double;border-color: rgb(23, 22, 24);background-position: center center;background-repeat: no-repeat;background-size: cover;background-image: url("http://pav7h2emv.bkt.clouddn.com/FnD-fHkNDLN1-b02XmnMvsz6ld-n");"><section class="" style="width: 100%;height: 100%;overflow: hidden;box-sizing: border-box;"><img class="" data-ratio="0.6012024" data-w="499" data-src="http://pav7h2emv.bkt.clouddn.com/FnD-fHkNDLN1-b02XmnMvsz6ld-n" style="opacity: 0; box-sizing: border-box; width: 100% !important; height: auto !important; visibility: visible !important;" width="100%" data-type="jpeg" _width="100%" src="http://pav7h2emv.bkt.clouddn.com/FnD-fHkNDLN1-b02XmnMvsz6ld-n" data-fail="0"></section></section></section></section><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: -30px 0% 30px;box-sizing: border-box;"><section class="" style="display: inline-block;vertical-align: top;width: 61.8%;padding: 0px 15px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: 40px 0% 0px;box-sizing: border-box;"><section class="" style="color: rgb(160, 160, 160);box-sizing: border-box;"><p style="margin: 0px;padding: 0px;box-sizing: border-box;">微信公眾號:</p><p style="margin: 0px;padding: 0px;box-sizing: border-box;">python測試開發圈</p><p style="margin: 0px;padding: 0px;box-sizing: border-box;"><br style="box-sizing: border-box;"></p></section></section></section></section><section class="" style="display: inline-block;vertical-align: top;width: 38.2%;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="text-align: center;margin: 10px 0% 0px;box-sizing: border-box;"><section class="" style="max-width: 100%;vertical-align: middle;display: inline-block;border-width: 0px;border-radius: 0px;box-shadow: rgb(0, 0, 0) 0px 0px 0px;width: 90%;overflow: hidden !important;box-sizing: border-box;"><img data-ratio="1" data-w="430" data-src="http://pav7h2emv.bkt.clouddn.com/FibGgIJSMfHtehzeWOOzjdQKSMx5" style="vertical-align: middle; max-width: 100%; box-sizing: border-box; width: 100% !important; height: auto !important; visibility: visible !important;" width="100%" data-type="jpeg" _width="100%" class="" src="http://pav7h2emv.bkt.clouddn.com/FibGgIJSMfHtehzeWOOzjdQKSMx5" data-fail="0"></section></section></section></section></section></section><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="margin: -30px 0% 0px;box-sizing: border-box;"><section class="" style="display: inline-block;vertical-align: top;width: 61.8%;padding: 0px 15px;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="transform: translate3d(5px, 0px, 0px);-webkit-transform: translate3d(5px, 0px, 0px);-moz-transform: translate3d(5px, 0px, 0px);-o-transform: translate3d(5px, 0px, 0px);box-sizing: border-box;"><section class="" style="color: rgb(160, 160, 160);font-size: 14px;box-sizing: border-box;"><p style="margin: 0px;padding: 0px;box-sizing: border-box;">一起分享學習與成長路線</p></section></section></section></section><section class="" style="display: inline-block;vertical-align: top;width: 38.2%;box-sizing: border-box;"><section class="" style="box-sizing: border-box;" powered-by="xiumi.us"><section class="" style="transform: translate3d(10px, 0px, 0px);-webkit-transform: translate3d(10px, 0px, 0px);-moz-transform: translate3d(10px, 0px, 0px);-o-transform: translate3d(10px, 0px, 0px);box-sizing: border-box;"><section class="" style="color: rgb(160, 160, 160);font-size: 14px;box-sizing: border-box;"><p style="margin: 0px;padding: 0px;box-sizing: border-box;">長按(或掃描)二維碼關注</p></section></section></section></section></section></section></section></section></section>