selenium主要功能封装
最近实习需要使用selenium这一自动化工具对公司的运维监控系统进行自动化爬取数据,编写代码过程中负责带我的杰哥让我参考借鉴他们公司外包的运维监控系统代码,在项目中我看到了对selenium主要各功能的封装重写,使用selenium过程中也体会到了该封装代码的便利性。
1 import time 2 from selenium.webdriver.support.wait import WebDriverWait 3 from selenium.webdriver.support import expected_conditions as EC 4 from selenium.webdriver.common.action_chains import ActionChains 5 from selenium.webdriver.common.by import By 6 7 #按钮点击 Brands是按钮的css选择器能定位的页面结构 8 def Clicks(driver, Brands, time_s=120): 9 time.sleep(0.5) 10 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 11 element.click() 12 13 14 #文本输入 contants是希望输入的文本内容 15 def TypeIns(driver, Brands, contants, time_s=120): 16 time.sleep(0.5) 17 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 18 element.clear() #将原文本内容清空 19 time.sleep(0.5) 20 element.send_keys(contants) 21 22 23 def TheDropDownChoices(driver, Brands, contants, time_s=120): 24 time.sleep(0.5) 25 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 26 element.select_by_visible_text(contants) 27 28 29 def TheDropDownChoicesIndex(driver, Brands, index, time_s=120): 30 time.sleep(0.5) 31 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 32 element.select_by_index(index) 33 34 35 def Hoverings(driver, Brands, time_s=120): 36 time.sleep(1) 37 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 38 ActionChains(driver).move_to_element(element).perform() 39 40 #根据css选择器由Brands定位的网页结构返回想要的文本内容 41 def InformationAcquisition(driver, Brands, time_s=120): 42 time.sleep(0.5) 43 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 44 return element.text 45 46 47 def InformationAcquisitions(driver, Brands, time_s=120): 48 time.sleep(0.5) 49 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 50 return element.text 51 52 #句柄切换到页面内置frame框架(selenium无法定位到页面内框架中元素) 53 #关于frame的切换和定位可参考 http://blog.csdn.net/huilan_same/article/details/52200586 54 def IframeCss(driver, Brands, time_s=120): 55 time.sleep(0.5) 56 element = WebDriverWait(driver, time_s, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR, Brands))) 57 driver.switch_to.frame(driver.find_element_by_css_selector(Brands)) 58