欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Selenium二次封装-Python版本

程序员文章站 2022-05-29 12:43:09
1 from selenium import webdriver 2 from selenium.webdriver.support.wait import WebDriverWait 3 from selenium.webdriver.support import expected_conditi... ......
  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')