python+selenium十:selenium的二次封裝

python+selenium十:基于原生selenium的二次封裝

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
# BY的用法
# driver.find_element("id", "kw")
# driver.find_element(By.ID, "kw")

class Bace():
'''基于原生的selenium做二次封裝'''

def __init__(self, driver:webdriver.Firefox): # driver:webdriver.Firefox:映射driver 為webdriver.Firefox
self.driver = driver
self.timeout = 10
self.t = 0.5

def find(self, locator, value=''):
''' 定位到元素,返回元素對象,沒定位到,Timeout異常 loctor 傳元祖,如("id", "kw") '''
if not isinstance(locator, tuple):
print('locator參數類型錯誤,必須傳元祖類型:loc = ("id", "value1")')
else:
print(f"正在定位元素信息:定位方式->{locator[0]}, 元素值->{locator[1]},value值->{value}")
if value != '': # value值定位
ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
return ele
else: # 默認為此常規定位方法
ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
if ele:
return ele
else:
print(f"定位失敗:定位方式->{locator[0]}, value值->{locator[1]}")
return False

def finds(self, locator, value=''):
''' 定位到元素,返回元素對象,沒定位到,Timeout異常 loctor 傳元祖,如("id", "kw") '''
if not isinstance(locator, tuple):
print('locator參數類型錯誤,必須傳元祖類型:loc = ("id", "value1")')
else:
print(f"正在定位元素信息:定位方式->{locator[0]}, 元素值->{locator[1]},value值->{value}")
if value != '': # value值定位
eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
return eles
else: # 默認為此常規定位方法
eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
if eles:
return eles
else:
print(f"定位失敗:定位方式->{locator[0]}, value值->{locator[1]}")
return []

def sendKeys(self, locator, text):
try:
self.find(locator).send_keys(text)
except:
print(f"輸入 {text} 失敗")

def click(self, locator):
try:
self.find(locator).click()
except:
print("點擊失敗")

def clear(self, locator):
try:
self.find(locator).clear()
except:
print("清空內容失敗")

def isSelected(self, locator, Type=''):
''' 判斷元素是否被選中,返回bool值 及點(選中/取消選中)'''
ele = self.find(locator)
try:
if Type == '': # 如果type參數為空,返回元素是否為選中狀態,True/False (默認)
r = ele.is_selected()
return r
elif Type == 'click': # 如果type參數為click,執行元素的點擊操作
ele.click()
else:
print(f"type參數 {Type} 錯誤,僅可為click或''")
except:
return False

def isElementExist(self, locator):
''' 判斷單個元素是否在DOM里面 (是否存在)'''
try:
self.find(locator)
return True
except:
return False

def isElementExists(self, locator):
''' 判斷一組元素是否在DOM里面 (是否存在),若不存在,返回一個空的list'''
eles = self.finds(locator)
n = len(eles)
if n == 0:
return False
elif n == 1:
return True
else:
print(f"定位到元素的個數:{n}")
return True

def title(self, title, Type='contains'):
''' 根據傳入的type類型判斷title '''
try:
if Type == 'is': # 判斷當前網頁title名為title 返回bool值
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
return result
elif Type == 'contains': # 判斷當前網頁title名含title 返回bool值 (默認)
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
return result
else:
print(f"type參數 {Type} 錯誤,僅可為is、contains")
except:
return False

def in_element(self, locator, value, Type='text'):
''' 根據傳入的type判斷內容是否在指定元素里面 '''
if not isinstance(locator, tuple):
print('locator參數類型錯誤,必須傳元祖類型:loc = ("id", "value1")')
try:
if Type == 'text': # 判斷當前獲取到的text含value 返回bool值 (默認)
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, value))
return result
elif Type == 'value': # 判斷當前獲取到的value含value 返回bool值, value為空字符串,返回False
result = self.find(locator, value)
return result
else:
print(f"type參數 {Type} 錯誤,僅可使用text或value屬性定位")
return False
except:
return False

def alert(self, timeout=3, Type=''):
''' 根據傳入的type判斷alert彈窗及操作 '''
result = WebDriverWait(self.driver, timeout, self.t).until(EC.alert_is_present())
try:
if Type == '': # 判斷alert是否存在,如果有,就返回alert對象 (默認)
if result:
return result
else:
print("alert不存在")
return False
elif Type == 'yes': # 執行alert的確定按鈕
result.accept()
elif Type == 'no': # 執行alert的取消按鈕
result.dismiss()
else:
print(f"type參數 {Type} 錯誤,僅可為yes、no、或''")
except:
return False

def get(self, locator, Type='text', name=''):
''' 根據傳入的type判斷獲取指定的內容 (title、text、attribute)
type==attribute: 獲取元素屬性 name:屬性 className、name、text、value··· '''
try:
if Type == 'title': # 獲取當前網頁 title
return self.driver.title
elif Type == 'text': # 獲取元素文本值(默認)
return self.find(locator).text
elif Type == 'attribute': # 獲取當前元素屬性
return self.find(locator).get_attribute(name)
else:
print(f"給的type參數 {Type} 錯誤,僅可用title、text、attribute")
except:
print(f"獲取 {Type} 值失敗")
return ''

def select(self, locator, value, Type='index'):
''' 下拉選項框 根據傳入的type值判斷(index、value、text) '''
element = self.find(locator) # 定位select這一欄
try:
if Type == 'index': # 用下標選擇 (默認)
Select(element).select_by_index(value)
elif Type == 'value': # 根據value值選擇
Select(element).select_by_value(value)
elif Type == 'text': # 根據選項的文本內容選擇
Select(element).select_by_visible_text(value)
else:
print(f"給的type參數 {Type} 錯誤,僅可為:int、text、value")
except:
print(f"根據 {value} 操作下拉框失敗")

def iframe(self, id_index_locator):
''' 常規切換 iframe'''
try:
if isinstance(id_index_locator, int): # 如果傳入的是數字,則以該數字為下標取值
self.driver.switch_to.frame(id_index_locator)
elif isinstance(id_index_locator, str): # 如果傳入的是字符串,則用iframe名字取值
self.driver.switch_to.frame(id_index_locator)
elif isinstance(id_index_locator, tuple): # 如果是元祖,則根據傳入的locator取值
ele = self.find(id_index_locator)
self.driver.switch_to.frame(ele)
except:
print("iframe切換異常")

def handle(self, value):
''' 句柄切換,index、句柄名 '''
try:
if isinstance(value, int): # 切換到該下標對應的窗口
handles = driver.window_handles
self.driver.switch_to.window(handles[value])
elif isinstance(value, str): # 切換到該句柄名稱對應的窗口
self.driver.switch_to.window(value)
else:
print(f"傳入的type參數 {value} 錯誤,僅可傳int、str")
except:
print(f"根據 {value} 獲取句柄失敗")

def move_to_element(self, locator):
''' 鼠標懸停操作 '''
try:
ele = self.find(locator)
ActionChains(self.driver).move_to_element(ele).perform()
except:
print("鼠標懸停操作失敗")
return False
'''==============================js與jQuery相關====================================='''

def js_focus_element(self, locator):
''' 聚焦元素 '''
target = self.find(locator)
self.driver.execute_script("arguments[0].scrollIntoView();", target)

def js_scroll_top(self):
''' 滾動到頂部 '''
js = "window.scrollTo(0,0)"
self.driver.execute_script(js)

def js_scroll_end(self, x=0):
''' 滾動到底部 '''
js = f"window.scrollTo({x},document.body.scrollHeight)"
self.driver.execute_script(js)

def js_find(self, action):
''' js查找元素,并做相應操作(默認id屬性) 輸入值:value='XXX' 點擊:click() '''
js = f"document.getElementById(“id”).{action}"
self.driver.execute_script(js)

def js_finds(self, Type, element, index, action):
''' js查找元素,并做相應操作 輸入值:value='XXX' 點擊:click()
js定位僅可為:id、Name、TagName、ClassName、Selector(CSS) '''
list = ['Name', 'TagName', 'ClassName', 'Selector']
if type in list:
print(f"正在執行js操作:定位方式->{Type}, 元素值->{element}, 下標值->{index}, 執行操作->{action}")
if type == 'Selector':
js = f'document.query{Type}All("{element}"){index}.{action}'
else:
js = f'document.getElementsBy{Type}({element})[{index}].{action};'
self.driver.execute_script(js)
else:
print(f"type參數 {Type} 錯誤,js定位僅可為:'Name'、'TagName'、'ClassName'、'Selector'(CSS)")

def js_readonly(self, idElement, value):
''' 去掉只讀屬性,并輸入內容 一般為id '''
js = f'document.getElementById({idElement}).removeAttribute("readonly");document.getElementById({idElement}).value="{value}"'
driver.execute_script(js)

def js_iframe(self, Type, element, action, index=''):
''' Js處理iframe 無需先切換到iframe上,再切回來操作
輸入值:value='' 點擊:click() type=id時,index='' '''
js = f'document.getElementBy{Type}({element}){index}.contentWindow.document.body.{action}'
driver.execute_script(js)
'''
jquery = '$(CSS).val("XXX");' # 根據css語法定位到元素,輸入內容
jquery = '$(CSS).val('');' # 清空
jquery = '$(CSS).click();' # 點擊
driver.execute_script(jquery)
'''

# def switch_alert(self):
# ''' 獲取alert彈窗 '''
# r = self.is_alert()
# if not r:
# print("alert不存在")
# else:
# return r

# def is_title(self, title):
# '''判斷當前title名為title 返回bool值'''
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
# return result
# except:
# return False
# def is_title_contains(self, title):
# '''判斷當前title名含title 返回bool值'''
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
# return result
# except:
# return False

# def is_text_in_element(self, locator, _text=''):
# '''判斷當前獲取到的text含_text='' 返回bool值'''
# if not isinstance(locator, tuple):
# print('locator參數類型錯誤,必須傳元祖類型:loc = ("id", "value1")')
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, _text))
# return result
# except:
# return False
# def is_value_in_element(self, locator, _value=''):
# '''返回bool值, value為空字符串,返回False'''
# if not isinstance(locator, tuple):
# print('locator參數類型錯誤,必須傳元祖類型:loc = ("id", "value1")')
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, _value))
# return result
# except:
# return False

# def get_title(self):
# '''獲取title'''
# return self.driver.title
# def get_text(self, locator):
# '''獲取文本'''
# try:
# t = self.find(locator).text
# return t
# except:
# print("獲取text失敗,返回'' ")
# return ""
# def get_attribute(self, locator, name):
# '''獲取屬性'''
# try:
# element = self.find(locator)
# return element.get_attribute(name)
# except:
# print("獲取%s屬性失敗,返回'' "%name)
# return ""

# def select_by_index(self, locator, index=0):
# '''通過索引,index是索引第幾個,從0開始,默認選第一個'''
# element = self.find(locator) # 定位select這一欄
# Select(element).select_by_index(index)

# def select_by_value(self, locator, value):
# '''通過value屬性'''
# element = self.find(locator)
# Select(element).select_by_value(value)

# def select_by_text(self, locator, text):
# '''通過文本值定位'''
# element = self.find(locator)
# Select(element).select_by_visible_text(text)

# def switch_handle_window_name(self, window_name):
# ''' 根據句柄名字切換句柄 '''
# self.driver.switch_to.window(window_name)
# def switch_handle_index(self, index):
# ''' 根據句柄下標切換句柄 '''
# handles = driver.window_handles
# self.driver.switch_to.window(handles[index])

# def js_find(self, action):
# '''
# 輸入值:value='XXX' 點擊:click()
# '''
# print("正在執行js操作,操作行為:%s"%action)
# js = "document.getElementById(“id”).%s"%action
# self.driver.execute_script(js)

if __name__ == "__main__":
driver = webdriver.Firefox()
driver.get("")
zentao = Base(driver)
# loc1 = (By.ID, "account")
# loc2 = (By.CSS_SELECTOR, "[name='password']")
# loc3 = (By.XPATH, "//*[@id='submit']")

loc1 = ("id", "account")
loc2 = ("css selector", "[name='password']")
loc3 = ("xpath", "//*[@id='submit']")
zentao.sendKeys(loc2, 123)

zentao.move_to_element(loc3)

轉載于:https://www.cnblogs.com/dwdw/p/9998660.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/450598.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/450598.shtml
英文地址,請注明出處:http://en.pswp.cn/news/450598.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

TDD開發模式實現代碼功能邏輯(自己總結,持續更新)

1.先寫測試 2.要使程序盡快的通過(及早交付) 3.優化程序結構,盡量使程序盡量快的運行 4.不要怕修改,單元測試會保證接口的正常運行 5.能通過測試后再去重構(消除冗余,優化程序設計) 6.用盡…

Intellij IDEA Debug調試技巧

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 1、這里以一個web工程為例,點擊圖中按鈕開始運行web工程。 2、設置斷點 3、使用postman發送http請求 4、請求發送之后會自動…

15行代碼讓蘋果設備崩潰,最新的iOS 12也無法幸免

安全研究人員Sabri Haddouche發現了一個只需幾行代碼就可以讓iPhone崩潰并重啟的方法。\\Sabri Haddouche在GitHub上發布了一個示例網頁,只有15行代碼,如果在iPhone或iPad上訪問這個頁面,就會崩潰并重啟。在macOS上使用Safari打開該頁面也會出…

appium更新到1.8.2,不能打開運行的解決辦法

1、更新下載appium 1.8.2 打開運行 一直是這個界面。很煩躁,重啟電腦或者卸載后重新安裝還是沒有用。 解決版本: 1、查看老版本和新版本的安裝位置 老版本默認是 C:\Program Files (x86)/appium安裝新的版本后,地址是:C:\Users…

C語言運算符及其優先級匯總表口訣

C語言運算符及其優先級匯總表口訣圓下箭頭一頓號非凡增減富強針地長三乘除,四加減,五移位千萬別把魚忘記,它在盛飯的廚子里小燈大燈燈燈不等爸喂魚,舅疑惑,裸雞也疑惑十三姨,十四父,十五逗&…

laraval如何使用tdd

1.首先新建一個laravel birdboard項目 composer create-project --prefer-dist birdboard 2.新建單元測試 php artisan make:test ProjectTest 3.書寫單元測試 對于初學著來說,最好先預測tdd即將要出現的錯誤,然后進行測試,判斷是否和自…

讓你頁面速度飛起來 Web前端性能優化

百度網盤下載 第1章 課程簡介對課程做簡單的介紹。第2章 資源合并與壓縮通過本章,我們學習和理解了web前端的概念,以及性能優化的意義所在,并且通過實戰中的壓縮與合并,深入理解了減少http請求數和減少http請求資源大小兩個優化要…

spring-data-JPA使用JpaRepository注解自定義SQL查詢數據庫多表查詢

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 一. 首先在Entity注解的類里面要寫好外鍵關系. 這個 ManyToOne 注解可以建立外鍵關系, 不要在自己傻傻的寫一個 private int grades_id…

工廠示例

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Reflection;namespace Common.DALFactory {/// <summary>/// 數據層對象實例創建/// </summary>public partial class DbFacto…

手把手教你如何優化C語言程序

程序進行優化&#xff0c;通常是指優化程序代碼或程序執行速度。優化代碼和優化速度實際上是一個予盾的統一&#xff0c;一般是優化了代碼的尺寸&#xff0c;就會帶來執行時間的增加&#xff0c;如果優化了程序的執行速度&#xff0c;通常會帶來代碼增加的副作用&#xff0c;很…

posman使用教程

1.新建文件夾 2.新建請求&#xff0c;右擊文件夾&#xff0c; 3.點開測試文件&#xff0c;有get,put,post方法&#xff0c;我經常使用的是put方法&#xff0c;區別我就不講了 4.我基本上填在body里面 5.這是基本的使用&#xff0c;我來更高級一點添加環境變量&#xff0c;一共有…

Linux實戰教學筆記42:squid代理與緩存實踐(一)

第1章 Squid介紹 1.1 緩存服務器介紹 緩存服務器&#xff08;英文意思cache server&#xff09;,即用來存儲&#xff08;介質為內存及硬盤&#xff09;用戶訪問的網頁&#xff0c;圖片&#xff0c;文件等等信息的專用服務器。這種服務器不僅可以使用戶可以最快的得到他們想要的…

Mysql中DATE_SUB 使用方法結合查詢一天內,一周內,一月內的信息實例講解

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 在對數據查詢或菜單時經常要對指定的時間或時間段進行查詢,例如要查詢一天內的信息,要查詢一周內的信息,要查詢一個月內的,南昌網站建設公…

mac電腦php中安裝swoole擴展件

1.首先更新php版本&#xff0c;如果已經是最新的請忽略&#xff0c; &#xff08;1&#xff09;查看是否安裝php brew search php &#xff08;2&#xff09;安裝最新版本php brew install php 2.查看是否安裝openssl&#xff0c;安裝了請忽略 &#xff08;1&#xff09;查看…

再談C語言指針—指向另一指針的指針

一、回顧指針概念 早在本書第貳篇中我就對指針的實質進行了闡述。今天我們又要學習一個叫做“指向另一指針地址”的指針。讓我們先回顧一下指針的概念吧&#xff01;當我們程序如下聲明變量&#xff1a;short int i;char a;short int * pi;程序會在內存某地址空間上為各變量開辟…

Java練習 SDUT-1586_計算組合數

計算組合數 Time Limit: 1000 ms Memory Limit: 32768 KiB Problem Description 計算組合數。C(n,m),表示從n個數中選擇m個的組合數。 計算公式如下&#xff1a; 若&#xff1a;m0&#xff0c;C(n,m)1 否則&#xff0c; 若 n1&#xff0c;C(n,m)1 否則&#xff0c;若mn&#xf…

mysql日期時間操作函數詳解

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 win7可以設定每周從哪一天開始&#xff0c;win2003等不能方便的修改。有的是周日開始&#xff0c;有的是周一開始。而工作中有的時候每周…

對C語言進行調試的最好方法是什么?

要了解調試程序的最好方法&#xff0c;首先要分析一下調試過程的三個要素&#xff1a;應該用什么工具調試一個程序?用什么辦法才能找出程序中的錯誤?怎樣才能從一開始就避免錯誤?應該用什么工具調試一個程序?有經驗的程序員會使用許多工具來幫助調試程序&#xff0c;包括一…

如何賦值hook定義的變量

1、定義變量 const { tableProps, mutate} useRequest(async (params {}) > {const { success, data, total } await Api.getUserAccountApi({page: params.current || 1,...searchValue,});return {list: success ? data : [],total: success ? total : 0,};},{pagin…

java中的sleep()和wait()的區別

對于sleep()方法&#xff0c;我們首先要知道該方法是屬于Thread類中的。而wait()方法&#xff0c;則是屬于Object類中的。sleep()方法導致了程序暫停執行指定的時間&#xff0c;讓出cpu該其他線程&#xff0c;但是他的監控狀態依然保持者&#xff0c;當指定的時間到了又會自動恢…