Selenium二次封装-Python版本

Posted 为你编程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Selenium二次封装-Python版本相关的知识,希望对你有一定的参考价值。

  1 from selenium import webdriver
  2 from selenium.webdriver.support.wait import WebDriverWait
  3 from selenium.webdriver.support import expected_conditions as EC
  4 from selenium.webdriver.common.by import By
  5 from selenium.webdriver.common.action_chains import ActionChains
  6 from selenium.webdriver.support.select import Select
  7 
  8 ‘‘‘
  9     对selenium进行二次封装
 10 ‘‘‘
 11 class PySelenium(object):
 12 
 13     ‘‘‘
 14         初始化,实例化浏览器驱动对象
 15     ‘‘‘
 16     def __init__(self, browser=ff):
 17         if browser == ff or browser == firefox: # 火狐
 18             driver = webdriver.Firefox()
 19         elif browser == chrome: # 谷歌
 20             option = webdriver.ChromeOptions()
 21             option.add_argument("--start-maximized")
 22             driver = webdriver.Chrome(chrome_options=option)
 23         elif browser == ie | browser == internet explorer: # IE
 24             driver = webdriver.Ie()
 25         elif browser == "opera":
 26             driver = webdriver.Opera()
 27         elif browser == "phantomjs":
 28             driver = webdriver.PhantomJS()
 29         elif browser == edge:
 30             driver = webdriver.Edge()
 31 
 32         try:
 33             self.driver = driver
 34         except Exception:
 35             # 手动抛出异常
 36             raise NameError(
 37                 "Not found %s browser,You can enter ‘ie‘, ‘ff‘, ‘opera‘, ‘phantomjs‘, ‘edge‘ or ‘chrome‘." % browser)
 38 
 39 
 40     ‘‘‘
 41         设置元素等待
 42     ‘‘‘
 43     def elementWait(self, css, secs=5):
 44         # 判断表达式是否包含指定字符
 45         if "=>" not in css:
 46             raise NameError("Positioning syntax errors, lack of ‘=>‘.")
 47 
 48         # 提取元素定位方式和定位表达式
 49         by = css.split("=>")[0]
 50         value = css.split("=>")[1]
 51 
 52         if by == "id":
 53             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located(By.ID,value))
 54         elif by == name:
 55             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located(By.NAME,value))
 56         elif by == "class":
 57             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.CLASS_NAME, value)))
 58         elif by == "link_text":
 59             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.LINK_TEXT, value)))
 60         elif by == "xpath":
 61             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.XPATH, value)))
 62         elif by == "css":
 63             WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR, value)))
 64         else:
 65             raise NameError(
 66                 "Please enter the correct targeting elements,‘id‘,‘name‘,‘class‘,‘link_text‘,‘xpath‘,‘css‘.")
 67 
 68     ‘‘‘
 69         获取指定元素对象
 70             表达式:  by=>value (by为定位方式,value为定位方式的表达式,例如:按照id定位某个元素,id=>"#")
 71     ‘‘‘
 72     def getElement(self, css):
 73         if "=>" not in css:
 74             raise NameError("Positioning syntax errors, lack of ‘=>‘.")
 75 
 76         by = css.split("=>")[0]
 77         value = css.split("=>")[1]
 78 
 79         if by == id:
 80             element = self.driver.find_element_by_id(value)
 81         elif by == name:
 82             element = self.driver.find_element_by_name(value)
 83         elif by == class:
 84             element = self.driver.find_element_by_class_name(value)
 85         elif by == link_text:
 86             element = self.driver.find_element_by_link_text(value)
 87         elif by == xpath:
 88             element = self.driver.find_element_by_xpath(value)
 89         elif by == css:
 90             element = self.driver.find_element_by_css_selector(value)
 91         else:
 92             raise NameError("Please enter the correct targeting elements,‘id‘,‘name‘,‘class‘,‘link_text‘,‘xpath‘,‘css‘.")
 93         return element
 94 
 95     ‘‘‘
 96         请求/打开指定链接
 97     ‘‘‘
 98     def openUrl(self, url):
 99         self.driver.get(url)
100 
101     ‘‘‘
102         窗口最大化
103     ‘‘‘
104     def maxWindows(self):
105         self.driver.maximize_window()
106 
107     ‘‘‘
108         设置窗口指定宽高
109     ‘‘‘
110     def setWindowsSize(self, wide, high):
111         self.driver.set_window_size(width=wide,height=high)
112 
113     ‘‘‘
114         添加文本到input
115     ‘‘‘
116     def addText(self, css, massage):
117         self.elementWait(css)
118         input = self.getElement(css)
119         input.send_keys(massage)
120 
121     ‘‘‘
122         清空input中的文本
123     ‘‘‘
124     def clear(self, css):
125         self.elementWait(css)
126         self.getElement(css).clear()
127 
128     ‘‘‘
129         鼠标左键单击
130     ‘‘‘
131     def click(self, css):
132         self.elementWait(css)
133         self.getElement(css).click()
134 
135     ‘‘‘
136         鼠标右键单击
137     ‘‘‘
138     def rightClick(self, css):
139         self.elementWait(css)
140         ActionChains(self.driver).context_click(self.getElement(css)).perform()
141 
142     ‘‘‘
143         移动鼠标到指定元素(默认在元素的中间位置)
144     ‘‘‘
145     def moveToTargetElement(self, css):
146         self.elementWait(css)
147         ActionChains(self.driver).move_to_element(self.getElement(css)).perform()
148 
149     ‘‘‘
150         移动鼠标到指定元素,并且指定位于元素的x,y偏移量(偏移量相对于元素的左上角)
151     ‘‘‘
152     def moveToTargetElementWithOffset(self, css, xoffset, yoffset):
153         self.elementWait(css)
154         ActionChains(self.driver).move_to_element_with_offset(self.getElement(css), xoffset, yoffset).perform()
155 
156     ‘‘‘
157         鼠标左键双击
158     ‘‘‘
159     def doubleClick(self, css):
160         self.elementWait(css)
161         ActionChains(self.driver).double_click(self.getElement(css)).perform()
162 
163     ‘‘‘
164         拖拽元素到指定元素处
165     ‘‘‘
166     def dragAndDropToElement(self, sourceCss, targetCss):
167         self.elementWait(sourceCss)
168         self.elementWait(targetCss)
169         ActionChains(self.driver).drag_and_drop(self.getElement(sourceCss),self.getElement(targetCss)).perform()
170 
171     ‘‘‘
172         拖拽元素指定偏移(该偏移是相对于当前鼠标的坐标偏移量)
173     ‘‘‘
174     def dragAndDropToOffset(self, sourceCss, xoffset, yoffset):
175         self.elementWait(sourceCss)
176         ActionChains(self.driver).drag_and_drop_by_offset(self.getElement(sourceCss), xoffset, yoffset).perform()
177 
178     ‘‘‘
179         鼠标左键点击链接文本
180     ‘‘‘
181     def clickLinkText(self, text):
182         self.driver.find_element_by_partial_link_text(text).click()
183 
184     ‘‘‘
185         关闭当前窗口
186     ‘‘‘
187     def close(self):
188         self.driver.close()
189 
190     ‘‘‘
191         关闭浏览器驱动
192     ‘‘‘
193     def quit(self):
194         self.driver.quit()
195 
196     ‘‘‘
197         提交指定表单
198     ‘‘‘
199     def submit(self, css):
200         self.elementWait(css)
201         self.getElement(css).submit()
202 
203     ‘‘‘
204         刷新当前页面,相当于点击F5
205     ‘‘‘
206     def F5(self):
207         self.driver.refresh()
208 
209     ‘‘‘
210         执行指定的js代码
211     ‘‘‘
212     def js(self, javaScript):
213         self.driver.execute_script(javaScript)
214 
215     ‘‘‘
216         获取指定元素的某个属性值
217     ‘‘‘
218     def getAttribute(self, css, attr):
219         self.elementWait(css)
220         self.getElement(css).get_attribute(attr)
221 
222     ‘‘‘
223         获取指定元素的文本内容,即value属性值
224     ‘‘‘
225     def getText(self, css):
226         self.elementWait(css)
227         self.getElement(css).text
228 
229     ‘‘‘
230         判断元素是否可见
231     ‘‘‘
232     def isDisplay(self, css):
233         self.elementWait(css)
234         return self.getElement(css).is_displayed()
235 
236     ‘‘‘
237         判断元素是否启用
238     ‘‘‘
239     def isEnabled(self, css):
240         self.elementWait(css)
241         return self.getElement(css).is_enabled()
242 
243     ‘‘‘
244         判断元素是否选中,一般用于验证checkbox和radio
245     ‘‘‘
246     def isSelected(self, css):
247         self.elementWait(css)
248         return self.getElement(css).is_selected()
249 
250     ‘‘‘
251         获取当前页面的title
252     ‘‘‘
253     def getTitle(self):
254         return self.driver.title
255 
256     ‘‘‘
257         获取当前页面的url
258     ‘‘‘
259     def getCurrentUrl(self):
260         return self.driver.current_url
261 
262     ‘‘‘
263         截图,保存到指定路径下文件中
264     ‘‘‘
265     def getScreenshot(self, fullFileName):
266         self.driver.get_screenshot_as_file(fullFileName)
267 
268     ‘‘‘
269         全局等待,Implicitly wait.All elements on the page.
270     ‘‘‘
271     def wait(self, secs):
272         self.driver.implicitly_wait(secs)
273 
274     ‘‘‘
275         弹框警告-确认
276     ‘‘‘
277     def alertAccept(self):
278         # self.driver.switch_to_alert().accept() 废弃的方式
279         self.driver.switch_to.alert.accept()
280 
281     ‘‘‘
282         弹框警告-取消
283     ‘‘‘
284     def alertDismiss(self):
285         # self.driver.switch_to_alert().dismiss() 废弃的方式
286         self.driver.switch_to.alert.dismiss()
287 
288     ‘‘‘
289         切换到指定的iframe
290     ‘‘‘
291     def switchFrame(self, css):
292         self.elementWait(css)
293         self.driver.switch_to.frame(self.getElement(css))
294 
295     ‘‘‘
296         切换到上一级(iframe)
297     ‘‘‘
298     def switchFrameOut(self):
299         self.driver.switch_to.default_content()
300 
301     ‘‘‘
302         打开新页面,并切换当前句柄为新页面的句柄
303         (每个页面对应一个句柄handle,可以通过self.driver.window_handles查看所有句柄)
304         --当前方法可能存在问题
305     ‘‘‘
306     def openNewWindow(self):
307         original_windows = self.driver.current_window_handle
308         all_handles = self.driver.window_handles
309         for handle in all_handles:
310             if handle != original_windows:
311                 self.driver.switch_to.window(handle)
312 
313 
314     ‘‘‘
315         等待元素,默认5秒,每1秒检查一次
316             --如果超时则对当前页面截图,以指定的文件名称保存到图片存储目录,并返回false
317     ‘‘‘
318     def waitEleAndSaveExceptionForTimeout(self, css, pictureName):
319         try:
320             self.elementWait(css)
321             return True
322         except Exception as e:
323             from conf.path import PICTUREPATH  # 导入定义的图片存储目录路径
324             pictureFullName = PICTUREPATH + pictureName + .jpg
325             self.getScreenshot(pictureFullName)
326             return False
327 
328     ‘‘‘
329         等待元素,10秒,每1秒检查一次
330             --如果超时,返回false
331     ‘‘‘
332     def waitEleAndExceptionForTimeout(self, css):
333         try:
334             self.element_wait(css, secs=10)
335             return True
336         except Exception as e:
337             return False
338 
339     ‘‘‘
340         根据指定的值选中相应的下拉列表中的选项
341             --如果没有指定的值则抛出异常
342     ‘‘‘
343     def selectByValue(self, css, value):
344         self.element_wait(css)
345         Select(self.get_element(css)).select_by_value(value)
346 
347 if __name__ == __main__:
348     pySelenium = PySelenium(chrome)

 

以上是关于Selenium二次封装-Python版本的主要内容,如果未能解决你的问题,请参考以下文章

Selenium2+python自动化63-二次封装(click/send_kesy)

python+selenium十:selenium的二次封装

Python+Selenium中级篇之3-二次封装Selenium中几个方法

Python+Selenium中级篇之7-把截图类方法封装到前面的BasePage.py

自动化测试框架中关于selenium api的二次封装

010 selenium 二次封装