2.定位操作的封装
针对我们已经学过的8种定位的方式,我们可以以参数的方式进行决定,这样能够更加灵活的进行操作
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 __del__(self):
time.sleep(5)
self.driver.quit()
if __name__ == '__main__':
web = Mylib('Firefox')
web.open_url('http://www.baidu.com')
el = web.locate_element('id','kw')
el.send_keys('itcast')
el_sub = web.locate_element('id','su')
el_sub.click()