from selenium import webdriver
import selenium
# 定义一个要使用的类
class WebKey:
def __init__(self):
self.driver = None
# 封装浏览器,支持三种浏览器
# br:gc=谷歌浏览器,ff=Firefox浏览器,ie=IE浏览器
def open_browser(self, br='gc'):
# 当br==gc,打开谷歌浏览器,br==ff打开Firefox浏览器,br==ie打开IE浏览器
if br == 'gc':
self.driver = webdriver.Chrome()
elif br == 'ff':
self.driver = webdriver.Firefox()
elif br == 'ie':
self.driver = webdriver.Ie()
else:
print('无该浏览器')
# 默认隐式等待10s
self.driver.implicitly_wait(10)
return self.driver
# 封装八种定位方式,分别是xpath、id、name、tag_name、link_text、partial_link_text,class_name,class_selector
def __find_ele(self, locator=''):
"""
支持八种定位方式
:param locator:
:return:
"""
# 定义ele为空
ele = None
self.ele = None
if locator.startswith('xpath='):
ele = self.driver.find_element_by_xpath(locator[locator.find('=')+1:])
elif locator.startswith('id='):
ele = self.driver.find_element_by_id(locator[locator.find('=')+1:])
elif locator.startswith('name='):
ele = self.driver.find_element_by_name(locator[locator.find('=')+1:])
elif locator.startswith('tag_name='):
ele = self.driver.find_element_by_tag_name(locator[locator.find('=')+1:])
elif locator.startswith('link_text='):
ele = self.driver.find_element_by_link_text(locator[locator.find('=')+1:])
elif locator.startswith('partial_link_text='):
ele = self.driver.find_element_by_partial_link_text(locator[locator.find('=')+1:])
elif locator.startswith('css_selector='):
ele = self.driver.find_element_by_css_selector(locator[locator.find('=')+1:])
elif locator.startswith('css_name='):
ele = self.driver.find_element_by_css_name(locator[locator.find('=') + 1:])
else:
ele = self.driver.find_element_by_xpath(locator)
self.ele = ele
return ele
# click点击封装
def click(self, locator=None):
"""
:pargram locator: 定位器,默认xpath
"""
ele = self.__find_ele(locator)
ele.click()
# input 输入框,输入封装
def input(self, locator=None, value=None):
"""
找到元素并完成输入
:param locator: 定位器,默认xpath
:param value:需要输入的字符串
:return
"""
ele = self.__find_ele(locator)
ele.send_keys(str(value))
# frame 封装
def into_frame(self, locator=None):
"""
进入iframe
:param locator:
:return:
"""
ele = self.__find_ele(locator)
self.driver.swich_to.frame(ele)
# 输入地址封装
def geturl(self, url=''):
self.driver.get(url)
selenium 常用封装-八种常用定位方式
最新推荐文章于 2024-05-17 15:05:27 发布