selenium学习--关键字驱动

可以使用关键字驱动避免句式上的冗余

# 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值