标签:page and text browser 自己 logs tle window method
framework包中文件如下所示:
base_page.py:常用操作方法
在framework包下创建base_page.py文件,文件中封装一些页面常用操作方法,可以自己在这个类中进行对应方法的添加,代码如下:
1 # coding=utf-8
2 import time
3 from selenium.common.exceptions import NoSuchElementException
4 import os.path
5 from framework.logger import Logger
6
7 # create a logger instance
8 logger = Logger(logger="BasePage").getlog()
9
10
11 class BasePage(object):
12 """
13 定义一个页面基类,让所有页面都继承这个类,封装一些常用的页面操作方法到这个类
14 """
15
16 def __init__(self, driver):
17 self.driver = driver
18
19 # quit browser and end testing
20 def quit_browser(self):
21 self.driver.quit()
22
23 # 浏览器前进操作
24 def forward(self):
25 self.driver.forward()
26 logger.info("Click forward on current page.")
27
28 # 浏览器后退操作
29 def back(self):
30 self.driver.back()
31 logger.info("Click back on current page.")
32
33 # 隐式等待
34 def wait(self, seconds):
35 self.driver.implicitly_wait(seconds)
36 logger.info("wait for %d seconds." % seconds)
37
38 # 点击关闭当前窗口
39 def close(self):
40 try:
41 self.driver.close()
42 logger.info("Closing and quit the browser.")
43 except NameError as e:
44 logger.error("Failed to quit the browser with %s" % e)
45
46 # 保存图片
47 def get_windows_img(self):
48 """
49 在这里我们把file_path这个参数写死,直接保存到我们项目根目录的一个文件夹.\Screenshots下
50 """
51 file_path = os.path.dirname(os.path.abspath(‘.‘)) + ‘\screenshots\\‘
52 rq = time.strftime(‘%Y%m%d%H%M%S‘, time.localtime(time.time()))
53 screen_name = file_path + rq + ‘.png‘
54 try:
55 self.driver.get_screenshot_as_file(screen_name)
56 logger.info("Had take screenshot and save to folder : \screenshots")
57 except NameError as e:
58 logger.error("Failed to take screenshot! %s" % e)
59 self.get_windows_img()
60
61 # 定位元素方法
62 def find_element(self, selector):
63 """
64 这个地方为什么是根据=>来切割字符串,请看页面里定位元素的方法
65 submit_btn = "id=>su"
66 login_lnk = "xpath => //*[@id=‘u1‘]/a[7]" # 百度首页登录链接定位
67 如果采用等号,结果很多xpath表达式中包含一个=,这样会造成切割不准确,影响元素定位
68 :param selector:
69 :return: element
70 """
71 element = ‘‘
72 if ‘=>‘ not in selector:
73 return self.driver.find_element_by_id(selector)
74 selector_by = selector.split(‘=>‘)[0]
75 selector_value = selector.split(‘=>‘)[1]
76
77 if selector_by == "i" or selector_by == ‘id‘:
78 try:
79 element = self.driver.find_element_by_id(selector_value)
80 logger.info("Had find the element \‘ %s \‘ successful "
81 "by %s via value: %s " % (element.text, selector_by, selector_value))
82 except NoSuchElementException as e:
83 logger.error("NoSuchElementException: %s" %