Selenium二次封裝-Python版本

為你程式設計發表於2018-08-29
  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`)

 

相關文章