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
# Create a logger instance
logger = Logger(logger="BasePage").getlog()
class BasePage(object):
"""Define a page base class, let all pages inherit this class, and encapsulate some common page operation methods into this class."""
def __init__(self, driver):
self.driver = driver
# Close the browser, usually after the end of the test
def quit_browser(self):
self.driver.quit()
logger.info("The test is over, close the browser")
# browser forward operation
def froward(self):
self.driver.forward()
logger.info("Click [Forward] on the current page")
# Browser back operation
def back(self):
self.driver.back()
logger.info("Click [Back] on the current page")
# implicit wait
def wait(self, seconds):
self.driver.implicitly_wait(seconds)
logger.info("Wait for %d seconds", seconds)
# Click to close the current window
def close(self):
try:
self.driver.close()
logger.info("Close and exit the browser")
except NameError as e:
logger.error("Browser exit failed %s" % e)
# save Picture
def get_windows_img(self):
"""Here we write the file_path parameter to death and save it directly to a file .\Screenshots in the root directory of our project"""
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("The screenshot has been saved to %s" % file_path)
except NameError as e:
logger.error("Failed to capture %s" % e)
self.get_windows_img()
# positioning element method
def find_element(self, selector):
"""Is this place is to cut the string according to =>
submit_btn=>"id=>su"
login_lnk = "xpath => //*[@id=''u1]/a[7]" # Baidu login link positioning
If the equal sign is used, the result will contain an = in many xpath expressions, which will cause inaccurate cutting
Affect element positioning
"""
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("Successfully found %s element through %s, the value is %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("Successfully found %s element, the value of %s is %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("Please enter a valid element type")
return element
# get input
def type(self, selector, text):
el = self.find_element(selector)
# el.clear()
try:
el.send_keys(text)
logger.info("The content in the input box is: %s" % text)
except NameError as e:
logger.info("Failed to enter input box", format(e))
self.get_windows_img()
# Get the dropdown box content
def select_xia(self, selector, text):
el = self.find_element(selector)
try:
Select(el).select_by_visible_text(text)
logger.info("The drop-down box information is obtained successfully, the content is %s", el.text)
except Exception as e:
logger.info("Failed to get pull-down information %s" % e)
# clear textbox
def clear(self, selector):
el = self.find_element(selector)
try:
el.clear()
logger.info("The content of the previous input box has been cleared")
except NameError as e:
logger.error("Failed to clear the content of the input box, the reason for the failure: %s" % e)
self.get_windows_img()
# click element
def click(self, selector):
el = self.find_element(selector)
try:
el.click()
if el.text() is None:
logger.info("Click %s succeeded" % el.text())
else:
logger.info("click success")
except NameError as e:
logger.info("Click failure reason: %s" % e)
# refresh page
def refresh(self):
self.driver.refresh()
logger.info("Page refreshing")
# mouseover
def move(self, selector):
el = self.find_element(selector)
try:
ActionChains(self.driver).move_to_element(el).perform()
logger.info("The mouse has hovered over %s" % el.text)
except Exception as e:
logger.info("Hover failure reason: %s" % e)
# right click
def right_click(self, selector):
el = self.find_element(selector)
try:
ActionChains(self.driver).double_click(el).perform()
logger.info("The mouse has been right-clicked successfully %s" % el.text)
except Exception as e:
logger.info("Double-click failure reason %S" % e)
# Mouse double click operation
def double_click(self, selector):
el = self.find_element(selector)
try:
logger.info("%s is about to be double-clicked" % el.text)
ActionChains(self.driver).context_click(el).perform()
logger.info("Double-click succeeded")
except Exception as e:
logger.info("Right-click failure reason %S" % e)
# Mouse drag and drop operation
def drag_anddrop(self, selector, selector2):
# Position the original position of the element
element = self.find_element(selector)
# Position the target position to move the element to
target = self.find_element(selector2)
# Perform drag and drop operations on elements
try:
ActionChains(self.driver).drag_and_drop(element, target).perform()
logger.info("%s drag and drop succeeded" % element.text)
except Exception as e:
logger.info("Drag and drop failure reason %s" % e)
# Get the page title
def get_page_title(self):
logger.info("The title of the current page is: %s" % self.driver.title)
return self.driver.title
# Get the current handle
def get_handle(self):
logger.info("The current handle is: %s"%self.driver.current_window_handle)
return self.driver.current_window_handle
# switch handle
def sent_handle(self):
# get all handles
all_h = self.driver.window_handles
# Get the current handle
h = self.driver.current_window_handle
# Loop to determine whether it is the same as the first handle
for i in all_h:
if i != h:
# switch if not equal to the first handle
logger.info("Switch handle")
self.driver.switch_to_window(i)
# Get the current page url
def get_curr_url(self):
logger.info("The url of the current page is: %s " % self.driver.current_url)
return self.driver.current_url
# Check the checkbox
def checkboxes(self, selector):
el = self.find_element(selector)
try:
for checkbox in el:
checkbox.click()
time.sleep(1)
logger.info("Check box checked successfully")
except Exception as e :
logger("The reason why the check failed %s" % e)
# upload files
def send_file(self, selector, file_path):
el = self.find_element(selector)
try:
el.send_keys(file_path)
logger.info("File uploaded successfully")
except Exception as e:
logger.info("File upload failed %s" % e)
# Date control handling
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, set to empty
self.driver.execute_script(js)
el.send_keys(text)
# sleeping time
@staticmethod
def sleep(seconds):
time.sleep(seconds)
logger.info("Sleep %s seconds" % seconds)