from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time class BasePage(object): """BasePage封装所有页面的公有方法,例如url、driver、find_element""" # 构造函数里面的参数就是类的所有参数 def __init__(self,selenuime_driver,base_url): self.driver = selenuime_driver self.url = base_url # 定义open()方法,调用_open()方法 def open(self): self.driver.get(self.url) self.driver.maximize_window() # 重写find_element()方法,参数为任意数量的(带*的参数) # 此方法是为了保证元素是可见的 def find_emelemt(self,*loc): try: # 保证元素可见 WebDriverWait(self.driver,10).until(EC.visibility_of_all_elements_located(loc)) return self.driver.find_element(*loc) except: print('定位错误') # 重新定义send_keys()方法,为了保证搜索按钮是否存在,还有有的输入框中默认有值,要清空 def send_keys(self,loc): self.find_emelemt(*loc).send_keys('中国') def button_click(self,loc): self.find_emelemt(*loc).click() def quit(self): self.driver.quit() if __name__ == "__main__": selenium_driver = webdriver.Firefox() url = 'http://www.baidu.com' xs = BasePage(selenium_driver,url) xs.open() time.sleep(10) text = ('id','kw') xs.send_keys(text) dj = ('id','su') xs.button_click(dj) time.sleep(10) xs.quit()