Selenium-WebDriverApi接口詳解


瀏覽器操作

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

獲取標簽元素

獲取標簽元素常用的一共有8種定位方式,而Selenium實際提供了18種定位方式,還有8中是上面的復數形式

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

  

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()

常見異常

oSuchElementException:沒有找到元素
 
NoSuchFrameException:沒有找到iframe
 
NoSuchWindowException:沒找到窗口句柄handle
 
NoSuchAttributeException:屬性錯誤
 
NoAlertPresentException:沒找到alert彈出框
 
ElmentNotVisibleException:元素不可見
 
ElementNotSelectableException:元素沒有被選中
 
TimeoutException:查找元素超時

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM