1. 程式人生 > >Selenium:WebDriverApi介面詳解

Selenium:WebDriverApi介面詳解

瀏覽器操作

# 重新整理
driver.refresh()
 
# 前進
driver.forward()
 
# 後退
driver.back()

Cookie操作

# 根據cookieKey,獲取cookie資訊
cookie = driver.get_cookie('cookieKey')
 
# 獲取所有cookie資訊
cookies = driver.get_cookies()
 
# 新增cookie,嚴格按照格式新增,cookie的key為name,value為value
driver.add_cookie({'name':'tmp
','value':'123123123'}) # 刪除所有cookie資訊 driver.delete_all_cookies() # 根據cookieKey刪除對應cookie driver.delete_cookie('UiCode')

 視窗操作

# 獲取當前瀏覽器的大小
driver.get_window_size()
 
# 通過畫素設定瀏覽器的大小
driver.set_window_size('width','height')
 
# 獲取當前視窗針對於Windows的位置的座標x,y
driver.get_window_position()
 
# 設定當前視窗針對Windows的位置,x,y driver.set_window_position(20,20) # 最大化當前視窗,不需要傳參 driver.maximize_window() # 返回當前操作的瀏覽器控制代碼 driver.current_window_handle # 返回所有開啟server的瀏覽器控制代碼 driver.window_handles

擷取當前頁面

# 獲取當前頁面的二進位制圖片資料,需要自己去寫入檔案
driver.get_screenshot_as_png()
 
# as_png的上層封裝,只需要傳入圖片名稱自動寫成圖片
driver.get_screenshot_as_file('fileName.png')

執行JavaScript語句

# 執行JavaScript語句
driver.execute_script('JavaScript Commond')
 
# 例:
# 通過js來操作滾動條
# 引數1:x  引數2: y
window.scrollTo(100,400);

關閉與退出

# 當開啟多個時,關閉當前頁面
driver.close()
 
# 退出並關閉所有頁面驅動
driver.quit()

其他

# 返回頁面原始碼
driver.page_source
 
# 返回tag標題
driver.title
 
# 返回當前Url
driver.current_url
 
# 獲取瀏覽器名稱 如:chrome
driver.name

ElementApi介面

# 根據標籤屬性名稱,獲取屬性value
element.get_attribute('style')
 
# 向輸入框輸入字串 如果input的type為file型別 可以輸入檔案絕對路徑上傳檔案
element.send_keys()
 
# 清除文字內容
element.clear()
 
# 滑鼠左鍵點選操作
element.click()
 
# 通過屬性名稱獲取屬性
element.get_property('id')
 
# 返回元素是否可見 True or False
element.is_displayed()
 
# 返回元素是否被選中 True or False
element.is_selected()
 
# 返回標籤元素的名字
element.tag_name
 
# 獲取當前標籤的寬和高
element.size
 
# 獲取元素的文字內容
element.text
 
# 模仿回車按鈕 提交資料
element.submit()
 
# 獲取當前元素的座標
element.location
 
# 擷取圖片
element.screenshot()

常見異常

NoSuchElementException:沒有找到元素
 
NoSuchFrameException:沒有找到iframe
 
NoSuchWindowException:沒找到視窗控制代碼handle
 
NoSuchAttributeException:屬性錯誤
 
NoAlertPresentException:沒找到alert彈出框
 
ElmentNotVisibleException:元素不可見
 
ElementNotSelectableException:元素沒有被選中
 
TimeoutException:查詢元素超時