Selenium ---- webdriver 常用的接口

瀏覽器操作

 刷新
driver.refresh()
 
 前進
driver.forward()
 
 後退
driver.back()

獲取標籤元素

 通過ID定位目標元素
driver.find_element_by_id('i1')
 
 通過className定位目標元素
driver.find_element_by_class_name('c1')
 
 通過name屬性定位目標元素
driver.find_element_by_name('n1')
 
 通過Xpath定位目標元素
driver.find_element_by_xpath('//*[@id="i1"]')
 
 通過css Selector定位目標元素
driver.find_element_by_css_selector('#i1')
 
 通過標籤名稱定位(注:在一個頁面中,標籤一定會重複,所以不用這個來進行定位)
driver.find_element_by_tag_name('input')
 
 通過標籤中的文本查找元素
driver.find_element_by_link_text('登錄')
 
 通過標籤中文本的模糊匹配查找
driver.find_elements_by_partial_link_text('錄')

獲取標籤元素常用的一共有8種定位方式,而Selenium實際提供了18種定位方式,還有8種是上面的複數形式,這裏就不一一介紹了,實際運用中並不常用,還有2種實際上是這上面所說16種的底層封裝。參數化的一種調用方式而已。

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語句

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

關閉與退出

 當開啓多個時,關閉當前頁面
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:查找元素超時

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章