python selenium 框架说明_全新python selenium unittest 框架介绍

#-*- coding = UTF-8 -*-#Autohr : 叶松桥#File : base.py#project : Caps_UI_Test#time : 2020/11/27 18:39#Describe : 基础方法#---------------------------------------

importos,sysimportpsycopg2importlogging.configimporttime

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from selenium.webdriver.common.by importByfrom selenium.webdriver.support.wait importWebDriverWaitfrom selenium.webdriver.support importexpected_conditions as ECfrom selenium.common.exceptions importNoSuchFrameException,NoSuchWindowException,NoAlertPresentException,NoSuchElementException

CON_LOG= os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/config/log.conf'logging.config.fileConfig(CON_LOG)

logging=logging.getLogger()classBaseView(object):def __init__(self, driver):

self.driver=driver

self.base_url= 'http://mcenter.test.mall'self.timeout= 11

def_open(self, url):"""打开浏览器并访问URL地址

:param url: url地址

:return:"""url_= self.base_url +url

logging.info("this page is %s" %url_)

self.driver.maximize_window()

self.driver.get(url_)assert self.driver.current_url == url_, 'Did ont land on %s' %url_defopen(self):"""调用私有函数

:return:"""self._open(self.url)def __locate_Element_selector(self, selector):"""八种定位方式选择

:param selector: 传入的格式必须为:定位方式,定位元素值,顺序不可改变

:return: 返回定位方式"""selector_by= selector.split(',')[0].strip()

selector_value= selector.split(',')[1].strip()if selector_by in ('i', 'id'):

locator=(By.ID, selector_value)elif selector_by in ('n', 'name'):

locator=(By.NAME, selector_value)elif selector_by in ('c', 'class'):

locator=(By.CLASS_NAME, selector_value)elif selector_by in ('x', 'xpath'):

locator=(By.XPATH, selector_value)elif selector_by in ('s', 'css'):

locator=(By.CSS_SELECTOR, selector_value)elif selector_by in ('t', 'tag_name'):

locator=(By.TAG_NAME, selector_value)elif selector_by in ('l', 'link_text'):

locator=(By.LINK_TEXT, selector_value)elif selector_by in ('ll', 'partial_link_text'):

locator=(By.PARTIAL_LINK_TEXT, selector_value)else:raise Exception('selector Error')returnlocatordeffind_element(self, selector):"""单个元素定位

:param loc:定位方式和元素属性

:return:"""time.sleep(0.5)try:

loc= self.__locate_Element_selector(selector)

WebDriverWait(self.driver,10).until(EC.presence_of_element_located(loc))return self.driver.find_element(*loc)except:

logging.error('-------------定位异常{0}--------------'.format(selector))deffind_elements(self, selector):"""多个元素定位

:param loc:定位方式和元素属性

:return:"""time.sleep(0.5)try:

loc= self.__locate_Element_selector(selector)

WebDriverWait(self.driver,10).until(EC.presence_of_element_located(loc))return self.driver.find_elements(*loc)except:

logging.error('-------------定位异常{0}--------------'.format(selector))defselect_text(self, selector, text):"""点击指定文本

:param selector:定位到的一组元素

:param text: 想要点击的元素文本

:return:"""listtext=self.find_elements(selector)for i inlisttext:if i.text ==text:

i.click()break

else:

logging.error("没有找到想要的元素%s" %text)defswitch_frame(self, loc):"""多表单嵌套切换

:param loc: 传元素的属性值

:return: 定位到的元素"""

try:returnself.driver.switch_to_frame(loc)exceptNoSuchFrameException as msg:

logging.error("查找iframe异常-> {0}".format(msg))defswitch_windows(self, loc):"""多窗口切换

:param loc:

:return:"""

try:returnself.driver.switch_to_window(loc)exceptNoSuchWindowException as msg:

logging.error("查找窗口句柄handle异常-> {0}".format(msg))defswitch_alert(self):"""警告框处理

:return:"""

try:returnself.driver.switch_to_alert()exceptNoAlertPresentException as msg:

logging.error("查找alert弹出框异常-> {0}".format(msg))def get_element_attribute(self, selector: str, value='value') ->str:"""获取元素属性"""ele=self.find_element(selector)returnele.get_attribute(value)def execute_script(self, js) ->None:"""执行js脚本"""self.driver.execute_script(js)def exhibition_element(self, selector: str) ->None:"""将元素显示到可见窗口中"""ele=self.find_element(selector)

js= "arguments[0].scrollIntoView();"self.driver.execute_script(js, ele)defget_conceal_text(self, selector):"""获取一组元素文本,包含隐藏元素"""ele=self.find_elements(selector)

textlist=[]

js= "return arguments[0].textContent"

for i inele:#text = i.get_attribute('textContent') 效果相同

text =self.driver.execute_script(js, i)

textlist.append(text)returntextlistdefaddAttribute(self, selector, attributeName, value):'''封装向页面标签添加新属性的方法

调用JS给页面标签添加新属性,arguments[0]~arguments[2]分别

会用后面的element,attributeName和value参数进行替换

添加新属性的JS代码语法为:element.attributeName=value

比如input.name='test''''ele=self.find_element(selector)

self.driver.execute_script("arguments[0].%s=arguments[1]" %attributeName, ele, value)defsetAttribute(self, selector, attributeName, value):'''封装设置页面对象的属性值的方法

调用JS代码修改页面元素的属性值,arguments[0]~arguments[1]分别

会用后面的element,attributeName和value参数进行替换'''ele=self.find_element(selector)

self.driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])", ele, attributeName, value)def get_pgsql_database(self, sql, database='test库名'):"""连接数据库,返回查询数据"""conn= psycopg2.connect(database=database, user="postgres", password=None, host="192.168.0.202", port="5432")

cur=conn.cursor()

cur.execute(sql)

data=cur.fetchall()

cur.close()

logging.info(data)returndata#重写定义send_keys方法

def send_key(self, selector, value, clear_first=True, click_first=True):

loc= self.__locate_Element_selector(selector)try:#loc = getattr(self, "_%s" % loc) # getattr相当于实现self.loc

ifclick_first:

self.driver.find_element(*loc).click()ifclear_first:

self.driver.find_element(*loc).clear()

self.driver.find_element(*loc).send_keys(value)exceptAttributeError:

logging.error("%s 页面中未能找到 %s 元素" % (self, loc))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值