Day17-selenium的二次封装

将selenium里的一些常用功能做二次封装,可以使我们的代码更简洁易懂

  1 from selenium import webdriver
  2 from selenium.webdriver.common.action_chains import ActionChains
  3 from selenium.webdriver.support import expected_conditions as EC
  4 from selenium.webdriver.support.ui import WebDriverWait
  5 from selenium.webdriver.common.by import By
  6 from selenium.webdriver.support.select import Select
  7 
  8 
  9 class Pyse(object):
 10     '''
 11         Pyse framework for the main class, the original
 12     selenium provided by the method of the two packaging,
 13     making it easier to use.
 14     '''
 15     # 初始化函数,在实例化该类时,创建一个浏览器对象,默认为火狐浏览器
 16     def __init__(self, browser='ff'):
 17         '''
 18         Run class initialization method, the default is proper
 19         to drive the Firefox browser. Of course, you can also
 20         pass parameter for other browser, Chrome browser for the "Chrome",
 21         the Internet Explorer browser for "internet explorer" or "ie".
 22         '''
 23         if browser == "firefox" or browser == "ff":
 24             driver = webdriver.Firefox()
 25         elif browser == "chrome":
 26             option = webdriver.ChromeOptions()
 27             option.add_argument("--start-maximized")
 28             driver = webdriver.Chrome(chrome_options=option)
 29         elif browser == "internet explorer" or browser == "ie":
 30             driver = webdriver.Ie()
 31         elif browser == "opera":
 32             driver = webdriver.Opera()
 33         elif browser == "phantomjs":
 34             driver = webdriver.PhantomJS()
 35         elif browser == 'edge':
 36             driver = webdriver.Edge()
 37         try:
 38             self.driver = driver
 39         except Exception:
 40             raise NameError(
 41                 "Not found %s browser,You can enter 'ie', 'ff', 'opera', 'phantomjs', 'edge' or 'chrome'." % browser)
 42     # 元素定位等待,默认等待5秒,以 =》 符号分割字符串,前面为定位方式,后面为定位的值
 43     def element_wait(self, css, secs=5):
 44         '''
 45         Waiting for an element to display.
 46 
 47         Usage:
 48         driver.element_wait("css=>#el",10)
 49         '''
 50         if "=>" not in css:
 51             raise NameError("Positioning syntax errors, lack of '=>'.")
 52 
 53         by = css.split("=>")[0]
 54         value = css.split("=>")[1]
 55 
 56         if by == "id":
 57             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.ID, value)))
 58         elif by == "name":
 59             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.NAME, value)))
 60         elif by == "class":
 61             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.CLASS_NAME, value)))
 62         elif by == "link_text":
 63             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.LINK_TEXT, value)))
 64         elif by == "xpath":
 65             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.XPATH, value)))
 66         elif by == "css":
 67             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR, value)))
 68         else:
 69             raise NameError(
 70                 "Please enter the correct targeting elements,'id','name','class','link_text','xpath','css'.")
 71     # 获取定位的元素
 72     def get_element(self, css):
 73         '''
 74         Judge element positioning way, and returns the element.
 75         '''
 76         if "=>" not in css:
 77             raise NameError("Positioning syntax errors, lack of '=>'.")
 78 
 79         by = css.split("=>")[0]
 80         value = css.split("=>")[1]
 81 
 82         if by == "id":
 83             element = self.driver.find_element_by_id(value)
 84         elif by == "name":
 85             element = self.driver.find_element_by_name(value)
 86         elif by == "class":
 87             element = self.driver.find_element_by_class_name(value)
 88         elif by == "link_text":
 89             element = self.driver.find_element_by_link_text(value)
 90         elif by == "xpath":
 91             element = self.driver.find_element_by_xpath(value)
 92         elif by == "css":
 93             element = self.driver.find_element_by_css_selector(value)
 94         else:
 95             raise NameError(
 96                 "Please enter the correct targeting elements,'id','name','class','link_text','xpath','css'.")
 97         return element
 98     # 打开指定的url
 99     def open(self, url):
100         '''
101         open url.
102 
103         Usage:
104         driver.open("https://www.baidu.com")
105         '''
106         self.driver.get(url)
107         self.js('window.scrollTo(0, 0)')
108     # 窗口最大化
109     def max_window(self):
110         '''
111         Set browser window maximized.
112 
113         Usage:
114         driver.max_window()
115         '''
116         self.driver.maximize_window()
117     # 设置窗口尺寸
118     def set_window(self, wide, high):
119         '''
120         Set browser window wide and high.
121 
122         Usage:
123         driver.set_window(wide,high)
124         '''
125         self.driver.set_window_size(wide, high)
126     # 输入指定文本
127     def type(self, css, text):
128         '''
129         Operation input box.
130 
131         Usage:
132         driver.type("css=>#el","selenium")
133         '''
134         self.element_wait(css)
135         el = self.get_element(css)
136         el.send_keys(text)
137     # 清除文本
138     def clear(self, css):
139         '''
140         Clear the contents of the input box.
141 
142         Usage:
143         driver.clear("css=>#el")
144         '''
145         self.element_wait(css)
146         el = self.get_element(css)
147         el.clear()
148     # 点击某个元素
149     def click(self, css):
150         '''
151         It can click any text / image can be clicked
152         Connection, check box, radio buttons, and even drop-down box etc..
153 
154         Usage:
155         driver.click("css=>#el")
156         '''
157         self.element_wait(css)
158         el = self.get_element(css)
159         el.click()
160     # 右键点击  基本不用
161     def right_click(self, css):
162         '''
163         Right click element.
164 
165         Usage:
166         driver.right_click("css=>#el")
167         '''
168         self.element_wait(css)
169         el = self.get_element(css)
170         ActionChains(self.driver).context_click(el).perform()
171     # 移动到某个元素上
172     def move_to_element(self, css):
173         '''
174         Mouse over the element.
175 
176         Usage:
177         driver.move_to_element("css=>#el")
178         '''
179         self.element_wait(css)
180         el = self.get_element(css)
181         ActionChains(self.driver).move_to_element(el).perform()
182     # 双击
183     def double_click(self, css):
184         '''
185         Double click element.
186 
187         Usage:
188         driver.double_click("css=>#el")
189         '''
190         self.element_wait(css)
191         el = self.get_element(css)
192         ActionChains(self.driver).double_click(el).perform()
193     # 拖拽  有点用
194     def drag_and_drop(self, el_css, ta_css):
195         '''
196         Drags an element a certain distance and then drops it.
197 
198         Usage:
199         driver.drag_and_drop("css=>#el","css=>#ta")
200         '''
201         self.element_wait(el_css)
202         element = self.get_element(el_css)
203         self.element_wait(ta_css)
204         target = self.get_element(ta_css)
205         ActionChains(driver).drag_and_drop(element, target).perform()
206     # 点击文本
207     def click_text(self, text):
208         '''
209         Click the element by the link text
210 
211         Usage:
212         driver.click_text("新闻")
213         '''
214         self.driver.find_element_by_partial_link_text(text).click()
215     # 关闭当前窗口
216     def close(self):
217         '''
218         Simulates the user clicking the "close" button in the titlebar of a popup
219         window or tab.
220 
221         Usage:
222         driver.close()
223         '''
224         self.driver.close()
225     # 退出驱动, 关闭浏览器
226     def quit(self):
227         '''
228         Quit the driver and close all the windows.
229 
230         Usage:
231         driver.quit()
232         '''
233         self.driver.quit()
234     # 提交
235     def submit(self, css):
236         '''
237         Submit the specified form.
238 
239         Usage:
240         driver.submit("css=>#el")
241         '''
242         self.element_wait(css)
243         el = self.get_element(css)
244         el.submit()
245     # 刷新
246     def F5(self):
247         '''
248         Refresh the current page.
249 
250         Usage:
251         driver.F5()
252         '''
253         self.driver.refresh()
254     # 执行js语句  很有用
255     def js(self, script):
256         '''
257         Execute JavaScript scripts.
258 
259         Usage:
260         driver.js("window.scrollTo(200,1000);")
261         '''
262         self.driver.execute_script(script)
263     # 获取参数
264     def get_attribute(self, css, attribute):
265         '''
266         Gets the value of an element attribute.
267 
268         Usage:
269         driver.get_attribute("css=>#el","type")
270         '''
271         el = self.get_element(css)
272         return el.get_attribute(attribute)
273     # 获取文本
274     def get_text(self, css):
275         '''
276         Get element text information.
277 
278         Usage:
279         driver.get_text("css=>#el")
280         '''
281         self.element_wait(css)
282         el = self.get_element(css)
283         return el.text
284     # 获取元素的展示状态,即是否可见
285     def get_display(self, css):
286         '''
287         Gets the element to display,The return result is true or false.
288 
289         Usage:
290         driver.get_display("css=>#el")
291         '''
292         self.element_wait(css)
293         el = self.get_element(css)
294         return el.is_displayed()
295     # 获取标题
296     def get_title(self):
297         '''
298         Get window title.
299 
300         Usage:
301         driver.get_title()
302         '''
303         return self.driver.title
304     # 获取当前的url
305     def get_url(self):
306         '''
307         Get the URL address of the current page.
308 
309         Usage:
310         driver.get_url()
311         '''
312         return self.driver.current_url
313     # 截图
314     def get_windows_img(self, file_path):
315         '''
316         Get the current window screenshot.
317 
318         Usage:
319         driver.get_windows_img()
320         '''
321         self.driver.get_screenshot_as_file(file_path)
322     # 等待
323     def wait(self, secs):
324         '''
325         Implicitly wait.All elements on the page.
326 
327         Usage:
328         driver.wait(10)
329         '''
330         self.driver.implicitly_wait(secs)
331     # 确认alert
332     def accept_alert(self):
333         '''
334         Accept warning box.
335 
336         Usage:
337         driver.accept_alert()
338         '''
339         self.driver.switch_to.alert.accept()
340     # 取消alert
341     def dismiss_alert(self):
342         '''
343         Dismisses the alert available.
344 
345         Usage:
346         driver.dismiss_alert()
347         '''
348         self.driver.switch_to.alert.dismiss()
349     # 切换到frame
350     def switch_to_frame(self, css):
351         '''
352         Switch to the specified frame.
353 
354         Usage:
355         driver.switch_to_frame("css=>#el")
356         '''
357         self.element_wait(css)
358         iframe_el = self.get_element(css)
359         self.driver.switch_to.frame(iframe_el)
360     # 返回到最外层的frame
361     def switch_to_frame_out(self):
362         '''
363         Returns the current form machine form at the next higher level.
364         Corresponding relationship with switch_to_frame () method.
365 
366         Usage:
367         driver.switch_to_frame_out()
368         '''
369         self.driver.switch_to.default_content()
370     # 打开一个新窗口
371     def open_new_window(self):
372         '''
373         Open the new window and switch the handle to the newly opened window.
374 
375         Usage:
376         driver.open_new_window()
377         '''
378         original_windows = self.driver.current_window_handle
379         all_handles = self.driver.window_handles
380         for handle in all_handles:
381             if handle != original_windows:
382                 self.driver.switch_to.window(handle)
383 
384     # def _save_png(self, name):
385     #     self.get_windows_img(name)
386     # 等待元素,如果存在该元素返回True,如果不存在,截图并保存到指定路径
387     def wait_and_save_exception(self, css, name):
388         try:
389             self.element_wait(css, secs=5)
390             return True
391         except Exception as e:
392             WEBPICTUREPATH = r'D:\\'
393             self.get_windows_img(WEBPICTUREPATH + name + '.jpg')
394             return False
395     # 同上,只是不截图
396     def wait_and_exception(self, css):
397         try:
398             self.element_wait(css, secs=10)
399             return True
400         except Exception as e:
401             return False
402     # 选择下拉选项
403     def select_by_value(self, css, value):
404         self.element_wait(css)
405         el = self.get_element(css)
406         Select(el).select_by_value(value)
View Code

这样,在使用selenium的时候只需要把这个类导入到要用到的文件中就可以了,如果认为功能不够完善,可以再改进也是很方便的

posted @ 2018-07-20 09:30  飒蓝  阅读(182)  评论(0编辑  收藏  举报