python+selenium_页面的常用方法合集basepage
import time
from selenium.common.exceptions import NoSuchElementException
import os.path
from basework.logger import Logger
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select
# 创建一个logger实例
logger = Logger(logger="BasePage").getlog()
class BasePage(object):
"""定义一个页面基类,让所有页面都继承这个类,封装一些常用的页面操作方法到这个类"""
def __init__(self, driver):
self.driver = driver
# 关闭浏览器,一般在测试最后的时候后关闭的
def quit_browser(self):
self.driver.quit()
logger.info("测试结束,关闭浏览器")
# 浏览器前进操作
def froward(self):
self.driver.forward()
logger.info("点击当前页面上的【前进】")
# 浏览器后退操作
def back(self):
self.driver.back()
logger.info("点击当前页面上的【后退】")
# 隐式等待
def wait(self, seconds):
self.driver.implicitly_wait(seconds)
logger.info("等待%d秒", seconds)
# 点击关闭当前窗口
def close(self):
try:
self.driver.close()
logger.info("关闭并且退出浏览器")
except NameError as e:
logger.error("浏览器退出失败%s" % e)
# 保存图片
def get_windows_img(self):
"""在这里我们把file_path这个参数写死,直接保存到我们项目根目录的一个文件.\Screenshots下"""
file_path = os.path.dirname(os.getcwd())+'\Screenshots\\'
rq = time.strftime('%y%m%d %H%M', time.localtime(time.time()))
screen_name = file_path + rq + '.png'
try:
self.driver.get_screenshot_as_file(screen_name)
logger.info("截图已经保存到%s" % file_path)
except NameError as e:
logger.error("截图失败%s" % e)
self.get_windows_img()
# 定位元素方法
def find_element(self, selector):
"""这个地方为是么是根据=>来切割字符串
submit_btn=>"id=>su"
login_lnk = "xpath => //*[@id=''u1]/a[7]" # 百度登录链接定位
如果采用等号,结果很多xpath表达式中包含一个=,这样造成切割不准确
影响元素定位
"""
element = ''
if '=>' not in selector:
return self.driver.find_element_by_id(selector)
selector_by = selector.split('=>')[0]
selector_value = selector.split('=>')[1]
if selector_by == 'i' or selector_by == 'id':
try:
element = self.driver.find_element_by_id(selector_value)
logger.info("通过%s成功找到%s元素,值为%s" % (selector_by, element.text, selector_value))
except NoSuchElementException as e:
logger.error("NoSuchElementException:%s" % e)
self.get_windows_img()
elif selector_by == "n" or selector_by == 'name':
element = self.driver.find_element_by_name(selector_value)
elif selector_by == "c" or selector_by == 'class_name':
element = self.driver.find_element_by_class_name(selector_value)
elif selector_by == 'l' or selector_by == 'link_text':
element = self.driver.find_element_by_link_text(selector_value)
elif selector_by == 'p' or selector_by == 'partial_link_text':
element = self.driver.find_element_by_partial_link_text(selector_value)
elif selector_by == 't' or selector_by == 'tag_name':
element = self.driver.find_element_by_tag_name(selector_value)
elif selector_by == 'x' or selector_by == 'xpath':
try:
element = self.driver.find_element_by_xpath(selector_value)
logger.info("成功找到%s元素,通过%s的值为%s" % (element.text, selector_by, selector_value))
except NoSuchElementException as e:
logger.error("NoSuchElementException:%s" % e)
self.get_windows_img()
elif selector_by == "s" or selector_by == 'css_selector':
element = self.driver.find_element_by_css_selector(selector_value)
else:
raise NameError("请输入有效的元素类型")
return element
# 获取输入内容
def type(self, selector, text):
el = self.find_element(selector)
# el.clear()
try:
el.send_keys(text)
logger.info("在输入框中的内容是:%s" % text)
except NameError as e:
logger.info("未能输入输入框", format(e))
self.get_windows_img()
# 获取下拉框内容
def select_xia(self, selector, text):
el = self.find_element(selector)
try:
Select(el).select_by_visible_text(text)
logger.info("下拉框信息获取成功,内容为%s", el.text)
except Exception as e:
logger.info("获取下拉信息失败%s" % e)
# 清除文本框
def clear(self, selector):
el = self.find_element(selector)
try:
el.clear()
logger.info("已经清除之前输入框的内容")
except NameError as e:
logger.error("输入框内容清除失败,失败原因:%s" % e)
self.get_windows_img()
# 点击元素
def click(self, selector):
el = self.find_element(selector)
try:
el.click()
if el.text() is None:
logger.info("点击%s成功" % el.text())
else:
logger.info("点击成功")
except NameError as e:
logger.info("点击失败原因:%s" % e)
# 刷新页面
def refresh(self):
self.driver.refresh()
logger.info("页面刷新中")
# 鼠标悬停
def move(self, selector):
el = self.find_element(selector)
try:
ActionChains(self.driver).move_to_element(el).perform()
logger.info("鼠标已经悬停在%s上方" % el.text)
except Exception as e:
logger.info("悬停失败原因:%s" % e)
# 鼠标右击
def right_click(self, selector):
el = self.find_element(selector)
try:
ActionChains(self.driver).double_click(el).perform()
logger.info("鼠标已经右击成功%s" % el.text)
except Exception as e:
logger.info("鼠标双击失败原因%S" % e)
# 鼠标双击操作
def double_click(self, selector):
el = self.find_element(selector)
try:
logger.info("%s即将被双击" % el.text)
ActionChains(self.driver).context_click(el).perform()
logger.info("双击成功")
except Exception as e:
logger.info("鼠标右击失败原因%S" % e)
# 鼠标拖放操作
def drag_anddrop(self, selector, selector2):
# 定位元素的原位置
element = self.find_element(selector)
# 定位元素要移动到的目标位置
target = self.find_element(selector2)
# 执行元素的拖放操作
try:
ActionChains(self.driver).drag_and_drop(element, target).perform()
logger.info("%s拖放成功" % element.text)
except Exception as e:
logger.info("拖放失败原因%s" % e)
# 获取网页标题
def get_page_title(self):
logger.info("当前页面的标题是:%s" % self.driver.title)
return self.driver.title
# 获取当前句柄
def get_handle(self):
logger.info("当前的句柄是:%s"%self.driver.current_window_handle)
return self.driver.current_window_handle
# 切换句柄
def sent_handle(self):
# 获取所有的句柄
all_h = self.driver.window_handles
# 获取当前句柄
h = self.driver.current_window_handle
# 循环判断是否与首句柄相同
for i in all_h:
if i != h:
# 如果不等于首句柄则切换
logger.info("切换句柄")
self.driver.switch_to_window(i)
# 获取当前页面url
def get_curr_url(self):
logger.info("当前页面的url是:%s " % self.driver.current_url)
return self.driver.current_url
# 复选框的勾选
def checkboxes(self, selector):
el = self.find_element(selector)
try:
for checkbox in el:
checkbox.click()
time.sleep(1)
logger.info("复选框勾选成功")
except Exception as e :
logger("勾选失败的原因% s" % e)
# 上传文件
def send_file(self, selector, file_path):
el = self.find_element(selector)
try:
el.send_keys(file_path)
logger.info("文件上传成功")
except Exception as e:
logger.info("文件上传失败%s" % e)
# 日期控件处理
def send_times(self, selector, text):
el = self.find_element(selector)
self.driver.switch_to.frame('iframe')
js = "$('input[id=laydate_table]').attr('readonly','')" # 4.jQuery,设置为空
self.driver.execute_script(js)
el.send_keys(text)
# 睡眠时间
@staticmethod
def sleep(seconds):
time.sleep(seconds)
logger.info("睡眠%s秒" % seconds)