web自動化實戰-基類封裝原始碼
阿新 • • 發佈:2020-08-20
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import NoSuchElementException
class Base():
def __init__(self,driver:webdriver):
self.driver = driver
self.timeout = 10
self.poll_frequency = 1
def findElement(self, location):
element = WebDriverWait(self.driver, self.timeout, self.poll_frequency).\
until(lambda x: x.find_element(*location),message="元素定位失敗")return element
def clear_method(self, location):
element = self.findElement(location)
element.clear()
def click_method(self, location):
element = self.findElement(location)
print(element)
element.click()
def sendKey(self, location, value):
element = self.findElement(location)if isinstance(value, str):
element.send_keys(value)
elif isinstance(value,tuple): # 鍵盤操作 Keys.ENTER Keys.CONTROL, 'a'
element.send_keys(value)
else:
print("輸入格式錯誤")
return None
def submit_method(self, location):
element=self.findElement(location)
element.submit()
# 返回頁面text資訊
def text_method(self, location):
element = self.findElement(location)
return element.text
# 獲得輸入框的尺寸
def size_method(self, location):
element = self.findElement(location)
element.size
# 返回元素的屬性值
def getAttribute(self, location, value=None):
element=self.findElement(location)
try:
ele = element.get_attribute(value)
except NoSuchElementException:
print("未找到元素屬性")
return None
return ele
def isDisplayed(self, location):
element = self.findElement(location)
try:
ele = element.is_dispalyed()
return ele
except Exception:
print("元素不存在")
return None
def alert_method(self):
alert = self.driver.switch_to.alert
alert.accept()
# return alert.text
# iframe封裝
def iframe_method(self, location): # index type location list \dict\ tuple \int \str
if isinstance(location, int):
self.driver.switch_to.frame(index)
elif isinstance(location, tuple):
iframe = self.findElement(location)
self.driver.switch_to.frame(iframe)
elif isinstance(location, str):
iframe = self.findElement(type)
self.driver.switch_to.frame(iframe)
else:
print("無法定位到ifram")
# 退出frame
def out_iframe(self):
self.driver.switch_to.parent_frame()
# 滑鼠操作
def mouse_operation(self,location):
ele = self.findElement(location)
ActionChains(self.driver).move_to_element(ele).perform()
# 執行JavaScript指令碼
def js(self, script):
# js = "window.scrollTo(左邊距,上邊距);"
if isinstance(script, str):
self.driver.execute_script(script)
# 下拉框處理
def select_method(self, location, index=None):
ele = self.findElement(location)
if isinstance(index, int) or isinstance(index, str):
Select(ele).select_by_index(index)
# H5視訊播放
def H5_video(self,value, video):
# video=self.findElement(location)
if isinstance(value,str):
self.driver.execute_script(value,video)
# 滑動解鎖
def slide_unlock(self):
pass
# 多視窗切換
def current_window(self):
pass