python+selenium十:selenium的二次封裝
阿新 • • 發佈:2018-11-22
elements 相關 end 底部 base att () eat 存在
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)
python+selenium十:selenium的二次封裝