3.点击输入的封装

点击输入是我们经常的操作,这几步是需要限定为再进行相关操作的,我们也可以直接封装成一步搞定
from selenium import webdriver
import time

class Mylib(object):

    def __init__(self, brower):
        '''
            初始化浏览器对象
        '''
        # 根据传入的参数创建对应的浏览器对象,前提是所有的浏览器驱动都已经正确安装
        if brower == 'Firefox':
            self.driver = webdriver.Firefox()
        elif brower == 'Chrome':
            self.driver = webdriver.Chrome()
        elif brower == 'PhantomJS':
            self.driver = webdriver.PhantomJS()
        # 设置浏览器全屏
        self.driver.maximize_window()

    def delay(self):
        '''
            延迟等待
        '''
        self.driver.implicitly_wait(5)

    def open_url(self, url):
        '''
            访问网站
        '''
        self.driver.get(url)
        self.delay()
        print('访问:%s成功'%url)

    def locate_element(self, locate_type, value):
        '''
            通过参数定位一个元素,并返回
        '''
        el = None
        if locate_type == 'id':
            el = self.driver.find_element_by_id(value)
        elif locate_type == 'name':
            el = self.driver.find_element_by_name(value)
        elif locate_type == 'class_name':
            el = self.driver.find_element_by_class_name(value)
        elif locate_type == 'tag_name':
            el = self.driver.find_element_by_tag_name(value)
        elif locate_type == 'link_text':
            el = self.driver.find_element_by_link_text(value)
        elif locate_type == 'partial_link_name':
            el = self.driver.find_element_by_partial_link_text(value)
        elif locate_type == 'xpath':
            el = self.driver.find_element_by_xpath(value)
        elif locate_type == 'css':
            el = self.driver.find_element_by_css_selector(value)
        # 返回定位到的元素
        if el is not None:
            return el

    def click_element(self, locate_type, value):
        '''
            直接点击某一元素
        '''
        el = self.locate_element(locate_type, value)
        el.click()

    def input_date(self, locate_type, value, data):
        '''
            定位到输入框,并且输入数据
        '''
        el = self.locate_element(locate_type, value)
        el.send_keys(data)

    def back(self):
        self.driver.back()
        self.delay()
        print('后退到:%s'%self.driver.current_url)

    def forward(self):
        self.driver.forward()
        self.delay()
        print('前进到:%s' % self.driver.current_url)

    def __del__(self):
        time.sleep(5)
        self.driver.quit()

if __name__ == '__main__':
    web = Mylib()
    web.open_url('http://www.baidu.com')
    web.input_date('id', 'kw', 'selenium')
    web.click_element('id', 'su')