可以使用关键字驱动避免句式上的冗余
# encoding:utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest
import time
import re
from ddt import ddt, data, unpack
# 浏览器初始化
def init_web(type_str, url):
if type_str == 'Chrome':
# 创建 ChromeDriver实例对象
driver = webdriver.Chrome()
elif type_str == 'Firefox':
# 创建 FirefoxDriver实例对象
driver = webdriver.Firefox()
elif type_str == 'PhantomJS':
# 创建 PhantomJSDriver实例对象
driver = webdriver.PhantomJS()
# driver.implicitly_wait(time) 隐式等待
driver.implicitly_wait(10)
# driver.get(url=None)将定位给定的URL网页
driver.get(url)
return driver
# 关键字驱动
class TestKeys(object):
def __init__(self, type_str, url):
self.input_bar = None
self.driver = init_web(type_str, url)
# 关闭浏览器
def quit(self):
self.driver.quit()
'''
也可以使用self.driver.close()
'''
# 传递文本
def input_text(self, locator_type, locator, text, **kwargs):
if locator_type == 'x path':
self.input_bar = self.driver.find_element_by_xpath(locator)
elif locator_type == 'id':
self.input_bar = self.driver.find_element_by_id(locator)
elif locator_type == 'name':
self.input_bar = self.driver.find_element_by_name(locator)
elif locator_type == 'css':
self.input_bar = self.driver.find_element_by_css_selector(locator)
self.input_bar.send_keys(text)
# 点击
def click_element(self, locator_type, locator):
if locator_type == 'xpath':
self.driver.find_element_by_xpath(locator).click()
elif locator_type == 'id':
self.driver.find_element_by_id(locator).click()
elif locator_type == 'name':
self.driver.find_element_by_name(locator).click()
elif locator_type == 'css':
self.driver.find_element_by_css_selector(locator).click()
# 清空内容
def clear_element(self, locator_type, locator):
if locator_type == 'xpath':
self.driver.find_element_by_xpath(locator).clear()
elif locator_type == 'id':
self.driver.find_element_by_id(locator).clear()
elif locator_type == 'name':
self.driver.find_element_by_name(locator).clear()
elif locator_type == 'css':
self.driver.find_element_by_css_selector(locator).clear()
# 获取页面
def click_detail_url(self, locator_type, locator):
self.click_element(locator_type, locator)