Best Python code snippet using playwright-python
PageAction.py
Source:PageAction.py
1# encoding=utf-82# @time :2020/5/9 12:183# @Author :liulaing.song4# @Email :1056703204@qq.com5# @File :PageAction.py6# @explain:页é¢å¨ä½78from selenium import webdriver9import time10from selenium.webdriver.common.action_chains import ActionChains11from selenium.webdriver.support.ui import WebDriverWait12from selenium.webdriver.common.by import By13from selenium.webdriver.support import expected_conditions as EC14from util.Log import Log15from util.KeyBoardUtil import KeyboardKeys16from util.WebTable import Table17from util.ReplaceValue import ReplaceValue18from selenium.webdriver.common.keys import Keys1920# å®ä¹å
¨å±åé21driver = None222324class PageAction(object):2526 def __init__(self):27 self.log = Log()28 self.key = KeyboardKeys()29 self.rv = ReplaceValue()3031 def openBrowser(self, url):32 '''3334 :param url: è¾å
¥çå°å35 :return: æå¼æµè§å¨36 '''37 global driver38 try:39 # option = webdriver.ChromeOptions()40 # option.add_argument('--headless')41 # driver = webdriver.Chrome(chrome_options=option)42 driver = webdriver.Chrome()43 driver.maximize_window()44 except Exception as e:45 raise e46 try:47 driver.get(url)48 driver.implicitly_wait(10)49 except Exception as e:50 raise e5152 def pageMotion(self, motion=None, locatorExpression=None, hoverLocator=None, value=None, table=None):53 '''5455 :param motion: å¨ä½æ令56 :param locatorExpression: æä½å
ç´ å®ä½è¡¨è¾¾å¼57 :param hoverLocator:æ¬æµ®ç¹å»ä½ç½®å®ä½è¡¨è¾¾å¼58 :param value:59 :return:60 '''61 global driver62 if motion == "click":6364 locator = (By.XPATH, locatorExpression)65 try:66 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))67 except:68 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')69 try:70 # ç¹å»äºä»¶71 driver.find_element_by_xpath(locatorExpression).click()72 time.sleep(4)73 except:74 # print("æªæ¾å°" + locatorExpression + "ç¹å»äºä»¶çå
ç´ ")75 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')7677 elif motion == "click_bottom":78 locator = (By.XPATH, locatorExpression)79 try:80 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))81 except:82 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')83 try:84 # ç¹å»äºä»¶85 js = "var q=getElementByXPath(//div[@class='slider-bar']).scrollTop=0"86 driver.execute_script(js)87 time.sleep(2)88 driver.find_element_by_xpath(locatorExpression).click()89 time.sleep(4)90 except:91 # print("æªæ¾å°" + locatorExpression + "ç¹å»äºä»¶çå
ç´ ")92 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')93949596 elif motion == "click_top":97 locator = (By.XPATH, locatorExpression)98 try:99 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))100 except:101 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')102103 try:104 # ç¹å»äºä»¶105 js = "var q=getElementByXPath('//div[@class='slider-bar']').scrollTop=100000"106 driver.execute_script(js)107 time.sleep(2)108 driver.find_element_by_xpath(locatorExpression).click()109 time.sleep(4)110 except:111 # print("æªæ¾å°" + locatorExpression + "ç¹å»äºä»¶çå
ç´ ")112 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')113114 elif motion == "input":115116 locator = (By.XPATH, locatorExpression)117 try:118 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))119 except:120 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')121122 try:123 # æ¸
é¤è¾å
¥æ¡124 driver.find_element_by_xpath(locatorExpression).clear()125 # è¾å
¥å¼126 driver.find_element_by_xpath(locatorExpression).send_keys(value)127 time.sleep(2)128 except:129 # print("æªæ¾å°" + locatorExpression + "è¾å
¥äºä»¶çå
ç´ ")130 self.log.info('æªæ¾å°"' + locatorExpression + '"è¾å
¥äºä»¶çå®ä½å
ç´ ')131132 elif motion == "double_click":133134 locator = (By.XPATH, locatorExpression)135 try:136 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))137 except:138 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')139140 try:141 double = driver.find_element_by_xpath(locatorExpression)142 ActionChains(driver).double_click(double).perform()143 time.sleep(4)144 except:145 # print("æªæ¾å°" + locatorExpression + "åå»äºä»¶çå
ç´ ")146 self.log.info('æªæ¾å°' + locatorExpression + 'åå»äºä»¶çå®ä½å
ç´ ')147148149 elif motion == "double_click_esc":150151 locator = (By.XPATH, locatorExpression)152 try:153 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))154 except:155 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')156 try:157 double = driver.find_element_by_xpath(locatorExpression)158 ActionChains(driver).double_click(double).perform()159 time.sleep(4)160 ActionChains(driver).send_keys(Keys.ESCAPE).perform()161 time.sleep(2)162 except:163 # print("æªæ¾å°" + locatorExpression + "åå»äºä»¶çå
ç´ ")164 self.log.info('æªæ¾å°' + locatorExpression + 'åå»äºä»¶çå®ä½å
ç´ ')165166 elif motion == "hover":167168 locator = (By.XPATH, locatorExpression)169 try:170 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))171 except:172 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')173174 try:175 ydong = driver.find_element_by_xpath(locatorExpression)176 ActionChains(driver).move_to_element(ydong).perform()177 time.sleep(2)178 except:179 self.log.info('æªæ¾å°"' + locatorExpression + '"é¼ æ æ¬æµ®äºä»¶çå®ä½å
ç´ ')180181 # try:182 # driver.find_element_by_xpath(hoverLocator).click()183 # time.sleep(3)184 # except:185 # self.log.info('æªæ¾å°"' + hoverLocator + '"é¼ æ æ¬æµ®åç¹å»äºä»¶çå®ä½å
ç´ ')186187 # elif motion == "enter":188 # try:189 # self.key.oneKey("enter")190 # time.sleep(8)191 # except Exception as e:192 # self.log.info("模æenteræ¥é: %s" %e)193194 elif motion == "enter":195196 locator = (By.XPATH, locatorExpression)197 try:198 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))199 except:200 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')201202 try:203 driver.find_element_by_xpath(locatorExpression).send_keys(Keys.ENTER)204 time.sleep(5)205 except:206 self.log.info('æªæ¾å°"' + locatorExpression + '"å车é®äºä»¶çå®ä½å
ç´ ')207208 elif motion == "esc":209 try:210 self.key.oneKey("esc")211 time.sleep(2)212 except Exception as e:213 self.log.info("模æescæ¥é: %s" % e)214215 elif motion == "top":216 try:217 js = "var q=document.getElementById('main-scroll').scrollTop = 0"218 driver.execute_script(js)219 time.sleep(2)220 except Exception as e:221 self.log.info("页é¢ç½®é¡¶æ¥é: %s" % e)222223 # try:224 # driver.find_element_by_xpath(locatorExpression).click()225 # time.sleep(3)226 # except:227 # self.log.info('æªæ¾å°"' + locatorExpression + '"置顶åç¹å»äºä»¶çå®ä½å
ç´ ')228 elif motion == "click_esc":229230 locator = (By.XPATH, locatorExpression)231 try:232 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))233 except:234 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')235236 try:237 # ç¹å»äºä»¶238 driver.find_element_by_xpath(locatorExpression).click()239 time.sleep(9)240 ActionChains(driver).send_keys(Keys.ESCAPE).perform()241 time.sleep(2)242 except:243 # print("æªæ¾å°" + locatorExpression + "ç¹å»äºä»¶çå
ç´ ")244 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')245246 # try:247 # self.key.oneKey("esc")248 # time.sleep(2)249 # except Exception as e:250 # self.log.info("模æescæ¥é: %s" %e)251252 elif motion == "quit":253254 try:255 driver.quit()256 except Exception as e:257 self.log.info("éåºæµè§å¨å¤±è´¥: %s" % e)258259 elif motion == "text":260261 locator = (By.XPATH, locatorExpression)262 try:263 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))264 except:265 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')266267 try:268 text = driver.find_element_by_xpath(locatorExpression).text269 time.sleep(2)270 # print(text)271 return text272 except:273 self.log.info('æªæ¾å°"' + locatorExpression + '"å®ä½çå
ç´ ææ¬ä¿¡æ¯')274 # driver.quit()275276 elif motion == "attribute":277278 locator = (By.XPATH, locatorExpression)279 try:280 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))281 except:282 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')283284 try:285 text = driver.find_element_by_xpath(locatorExpression).get_attribute('value')286 time.sleep(2)287 # print(text)288 return text289 except:290 self.log.info('æªæ¾å°"' + locatorExpression + '"å®ä½çå
ç´ ææ¬ä¿¡æ¯')291292 elif motion == "table_cell":293294 locator = (By.XPATH, locatorExpression)295 try:296 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))297 except:298 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')299300 try:301 webTable = driver.find_element_by_xpath(locatorExpression)302 # listData = webTable.text303 tableMessage = Table(webTable)304 text = tableMessage.getCell(0, 5).text305 workNo = tableMessage.getCell(0, 4).text306 self.rv.keepValue(workNo)307 time.sleep(2)308 return text309 except:310 self.log.info('æªæ¾å°"' + locatorExpression + '"å®ä½çå
ç´ tableè¡¨æ ¼ä¿¡æ¯')311312 elif motion == "click_role":313314 locator = (By.XPATH, locatorExpression)315 try:316 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))317 except:318 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')319320 try:321 # ç¹å»äºä»¶322 driver.find_element_by_xpath(locatorExpression).click()323 time.sleep(5)324 except:325 # print("æªæ¾å°" + locatorExpression + "ç¹å»äºä»¶çå
ç´ ")326 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')327328 elif motion == "click_sleep":329330 locator = (By.XPATH, locatorExpression)331 try:332 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))333 except:334 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')335336 try:337 # ç¹å»äºä»¶338 driver.find_element_by_xpath(locatorExpression).click()339 time.sleep(10)340 except:341 # print("æªæ¾å°" + locatorExpression + "ç¹å»äºä»¶çå
ç´ ")342 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')343344 elif motion == "click_await":345346 locator = (By.XPATH, locatorExpression)347 try:348 WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located(locator))349 except:350 self.log.info('æªæ¾å°"' + locatorExpression + '"ç¹å»äºä»¶çå®ä½å
ç´ ')351352 try:353 text = driver.find_element_by_xpath(locatorExpression).text354 if "çå¾
æ±æ»" not in text:355 while True:356 driver.refresh()357 time.sleep(10)358 text = driver.find_element_by_xpath(locatorExpression).text359 if "çå¾
æ±æ»" in text:360 locator = (By.XPATH, "//i[@class='icon ikcon ikcon-iconfont iconpick-up']")361 WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located(locator))362 driver.find_element_by_xpath("//i[@class='icon ikcon ikcon-iconfont iconpick-up']").click()363 time.sleep(3)364 locator = (By.XPATH, "//i[@class='icon ikcon ikcon-iconfont iconexpand']")365 WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located(locator))366 driver.find_element_by_xpath("//i[@class='icon ikcon ikcon-iconfont iconexpand']").click()367 time.sleep(3)368 break369 except:370 self.log.info('æªæ¾å°"' + locatorExpression + '"å®ä½çå
ç´ ææ¬ä¿¡æ¯')371372373374375376 else:377 driver.quit()378 self.log.info("请æ£æ¥excel'å¨ä½'åæ¯å¦ä¹¦åæ£ç¡®")379380381if __name__ == "__main__":382 pa = PageAction()383 pa.openBrowser("http://uat.tijian.ikang.com")384 pa.pageMotion(motion="input", locatorExpression="//input[@placeholder='请è¾å
¥è´¦å·']", value="liuliangsong")385 pa.pageMotion(motion="input", locatorExpression="//input[@placeholder='请è¾å
¥å¯ç ']", value="123456")386 pa.pageMotion(motion="click", locatorExpression="//button[@type='button']")
...
selenium_driver.py
Source:selenium_driver.py
1from selenium.webdriver.common.by import By2from traceback import print_stack3from selenium.webdriver.support.select import Select4from selenium.webdriver.support.ui import WebDriverWait5from selenium.webdriver.support import expected_conditions as EC6from selenium.webdriver.common.action_chains import ActionChains7from selenium.common.exceptions import *8import utilities.custom_logger as cl9import logging10import time11import os12import allure13class SeleniumDriver():14 log = cl.customLogger(logging.DEBUG)15 def __init__(self, driver):16 self.driver = driver17 def screenShot(self, resultMessage):18 """19 Take a screenshot of the current open web page20 """21 fileName = resultMessage + "." + str(round(time.time() *1000)) + ".png"22 if len(fileName) >= 200:23 fileName = str(round(time.time() *1000)) + ".png"24 screenshotDirectory = "../screenshots/"25 relativeFileName = screenshotDirectory + fileName26 currentDirectory = os.path.dirname(__file__)27 destinationFile = os.path.join(currentDirectory, relativeFileName)28 destinationDirectory = os.path.join(currentDirectory, screenshotDirectory)29 try:30 if not os.path.exists(destinationDirectory):31 os.makedirs(destinationDirectory)32 self.driver.save_screenshot(destinationFile)33 allure.attach(self.driver.get_screenshot_as_png(),34 name=fileName,35 attachment_type=allure.attachment_type.PNG)36 self.log.info("Screenshot save to directory: " + destinationFile)37 except:38 self.log.error("### Exception Occurred when taking screenshot")39 print_stack()40 def getTitle(self):41 return self.driver.title42 def getByType(self, locatorType):43 locatorType = locatorType.lower()44 if locatorType == "id":45 return By.ID46 elif locatorType == "name":47 return By.NAME48 elif locatorType == "xpath":49 return By.XPATH50 elif locatorType == "css":51 return By.CSS_SELECTOR52 elif locatorType == "class":53 return By.CLASS_NAME54 elif locatorType == "link":55 return By.LINK_TEXT56 else:57 self.log.info("Locator type" + locatorType + "not correct/supported")58 return False59 def dropdownSelectElement(self, locator, locatorType="id", selector="", selectorType="value"):60 try:61 element = self.getElement(locator, locatorType)62 sel = Select(element)63 if selectorType == "value":64 sel.select_by_value(selector)65 time.sleep(1)66 elif selectorType == "index":67 sel.select_by_index(selector)68 time.sleep(1)69 elif selectorType == "text":70 sel.select_by_visible_text(selector)71 time.sleep(1)72 self.log.info("Element selected with selector: " + str(selector) +73 " and selectorType: " + selectorType)74 except:75 self.log.error("Element not selected with selector: " + str(selector) +76 " and selectorType: " + selectorType)77 print_stack()78 def getDropdownOptionsCount(self, locator, locatorType="id"):79 '''80 get the number of options of drop down list81 :return: number of Options of drop down list82 '''83 options = None84 try:85 element = self.getElement(locator, locatorType)86 sel = Select(element)87 options = sel.options88 self.log.info("Element found with locator: " + locator +89 " and locatorType: " + locatorType)90 except:91 self.log.error("Element not found with locator: " + locator +92 " and locatorType: " + locatorType)93 return options94 def getDropdownSelectedOptionText(self, locator, locatorType="id"):95 '''96 get the text of selected option in drop down list97 :return: the text of selected option in drop down list98 '''99 selectedOption_text = None100 try:101 element = self.getElement(locator, locatorType)102 sel = Select(element)103 selectedOption_text = sel.first_selected_option.text104 self.log.info("Return the selected option of drop down list with locator: " + locator +105 " and locatorType: " + locatorType)106 except:107 self.log.error("Can not return the selected option of drop down list with locator: " + locator +108 " and locatorType: " + locatorType)109 return selectedOption_text110 def getDropdownSelectedOptionValue(self, locator, locatorType="id"):111 '''112 get the value of selected option in drop down list113 :return: the value of selected option in drop down list114 '''115 selectedOption_value = None116 try:117 element = self.getElement(locator, locatorType)118 sel = Select(element)119 selectedOption_value = sel.first_selected_option.get_attribute("value")120 self.log.info("Return the selected option of drop down list with locator: " + locator +121 " and locatorType: " + locatorType)122 except:123 self.log.error("Can not return the selected option of drop down list with locator: " + locator +124 " and locatorType: " + locatorType)125 return selectedOption_value126 def getElement(self, locator, locatorType="id"):127 element = None128 try:129 locatorType = locatorType.lower()130 byType = self.getByType(locatorType)131 element = self.driver.find_element(byType, locator)132 self.log.info("Element found with locator: " + locator +133 " and locatorType: " + locatorType)134 except:135 self.log.error("Element not found with locator: " + locator +136 " and locatorType: " + locatorType)137 return element138 def isElementSelected(self, locator, locatorType):139 isSelected = None140 try:141 element = self.getElement(locator, locatorType)142 isSelected = element.is_selected()143 self.log.info("Element found with locator: " + locator +144 " and locatorType: " + locatorType)145 except:146 self.log.error("Element not found with locator: " + locator +147 " and locatorType: " + locatorType)148 return isSelected149 def getElementList(self, locator, locatorType="id"):150 """151 Get list of elements152 """153 element = None154 try:155 locatorType = locatorType.lower()156 byType = self.getByType(locatorType)157 element = self.driver.find_elements(byType, locator)158 self.log.info("Element list found with locator: " + locator +159 " and locatorType: " + locatorType)160 except:161 self.log.error("Element list not found with locator: " + locator +162 " and locatorType: " + locatorType)163 return element164 def elementClick(self, locator="", locatorType="id", element=None):165 """166 Either provide element or a combination of locator and locatorType167 """168 try:169 if locator:170 element = self.getElement(locator, locatorType)171 element.click()172 self.log.info("clicked on element with locator: " + locator +173 " locatorType: " + locatorType)174 except:175 self.log.error("cannot click on the element with locator: " + locator +176 " locatorType: " + locatorType)177 print_stack()178 def elementHover(self, locator="", locatorType="id", element=None):179 """180 Either provide element or a combination of locator and locatorType181 """182 try:183 if locator:184 element = self.getElement(locator, locatorType)185 hover = ActionChains(self.driver).move_to_element(element)186 hover.perform()187 time.sleep(2)188 self.log.info("hover to element with locator: " + locator +189 " locatorType: " + locatorType)190 except:191 self.log.error("cannot hover to the element with locator: " + locator +192 " locatorType: " + locatorType)193 print_stack()194 def sendKeys(self, data, locator="", locatorType="id", element=None):195 """196 Send keys to an element197 Either provide element or a combination of locator and locatorType198 """199 try:200 if locator:201 element = self.getElement(locator, locatorType)202 element.send_keys(data)203 self.log.info("send data on element with locator: " + locator +204 " locatorType: " + locatorType)205 except:206 self.log.error("cannot send data on the element with locator: " + locator +207 " locatorType: " + locatorType)208 print_stack()209 def clearKeys(self, locator="", locatorType="id", element=None):210 """211 Clear keys of an element212 Either provide element or a combination of locator and locatorType213 """214 try:215 if locator:216 element = self.getElement(locator, locatorType)217 element.clear()218 self.log.info("Clear data of element with locator: " + locator +219 " locatorType: " + locatorType)220 except:221 self.log.error("cannot clear data of the element with locator: " + locator +222 " locatorType: " + locatorType)223 print_stack()224 def getText(self, locator="", locatorType="id", element=None, info=""):225 """226 Get 'Text' on an element227 Either provide element or a combination of locator and locatorType228 """229 try:230 if locator:231 self.log.debug("In locator condition")232 element = self.getElement(locator, locatorType)233 self.log.debug("Before finding text")234 text = element.text235 self.log.debug("After finding element, size is: " + str(len(text)))236 if len(text) == 0:237 text = element.get_attribute("innerText")238 if len(text) !=0:239 self.log.info("Getting text on element :: " + info)240 self.log.info("The text is :: '" + text + "'")241 text = text.strip()242 except:243 self.log.error("Failed to get text on element " + info)244 print_stack()245 text = None246 return text247 def isElementPresent(self, locator="", locatorType="id", element=None):248 """249 Check if element is present250 Either provide element or a combination of locator and locatorType251 """252 try:253 if locator:254 element = self.getElement(locator, locatorType)255 if element is not None:256 self.log.info("Element found with locator: " + locator +257 " and locatorType: " + locatorType)258 return True259 else:260 self.log.error("Element not found with locator: " + locator +261 " and locatorType: " + locatorType)262 return False263 except:264 self.log.error("Element not found with locator: " + locator +265 " and locatorType: " + locatorType)266 return False267 def isElementDisplayed(self, locator="", locatorType="id", element=None):268 """269 Check if element is displayed270 Either provide element or a combination of locator and locatorType271 """272 isDisplayed = False273 try:274 if locator:275 element = self.getElement(locator, locatorType)276 if element is not None:277 isDisplayed = element.is_displayed()278 self.log.info("Element is displayed with locator: " + locator +279 " and locatorType: " + locatorType)280 else:281 self.log.error("Element is not displayed with locator: " + locator +282 " and locatorType: " + locatorType)283 return isDisplayed284 except:285 self.log.error("Element is not displayed with locator: " + locator +286 " and locatorType: " + locatorType)287 return False288 def elementPresenceCheck(self, locator="", locatorType="id"):289 try:290 locatorType = locatorType.lower()291 byType = self.getByType(locatorType)292 elementList = self.driver.find_elements(byType, locator)293 if len(elementList) > 0:294 self.log.info("Element Found")295 return True296 else:297 self.log.info("Element not found")298 return False299 except:300 self.log.info("Element not found")301 return False302 def waitForElement(self, locator, locatorType = 'id', timeout = 10, pollFrequency = 0.5 ):303 element = None304 try:305 self.log.info("Waiting for maximum :: " + str(timeout) + " :: seconds for element to be clickable")306 wait = WebDriverWait(self.driver, timeout, poll_frequency=pollFrequency,307 ignored_exceptions=[NoSuchElementException,308 ElementNotVisibleException,309 ElementNotSelectableException])310 ByType = self.getByType(locatorType)311 element = wait.until(EC.element_to_be_clickable((ByType,locator)))312 self.log.info("Element appeared on the web page")313 except:314 self.log.info("Element not appeared on the web page")315 print_stack()316 return element317 def webScroll(self, direction="up"):318 if direction == "up":319 # Scroll Up320 self.driver.execute_script("window.scrollBy(0, -1000);")321 if direction == "down":322 # Scroll Down323 self.driver.execute_script("window.scrollBy(0, 1000);")324 def getURL(self):325 '''326 Get the current URL327 :return: current URL328 '''329 currentURL = self.driver.current_url330 return currentURL331 def pageBack(self):332 '''333 page back the browser334 '''335 self.driver.execute_script("window.history.go(-1)")336 def getAttributeValue(self, locator="", locatorType="id", element=None, attribute=""):337 '''338 get attribute value339 '''340 try:341 if locator:342 self.log.debug("In locator condition")343 element = self.getElement(locator, locatorType)344 attribute_value = element.get_attribute(attribute)345 except:346 self.log.error("Failed to get " + attribute + " in element with locator: " +347 locator + " and locatorType: " + locatorType)348 print_stack()349 attribute_value = None350 return attribute_value351 def refresh(self):352 self.driver.get(self.driver.current_url)353 def page_has_loaded(self):354 try:355 WebDriverWait(self.driver, 1000, poll_frequency=0.5).until(lambda driver: self.driver.execute_script('return document.readyState == "complete";'))356 WebDriverWait(self.driver, 1000, poll_frequency=0.5).until(lambda driver: self.driver.execute_script('return jQuery.active == 0'))357 WebDriverWait(self.driver, 1000, poll_frequency=0.5).until(lambda driver: self.driver.execute_script('return typeof jQuery != "undefined"'))358 WebDriverWait(self.driver, 1000, poll_frequency=0.5).until(lambda driver: self.driver.execute_script('return angular.element(document).injector().get("$http").pendingRequests.length === 0'))359 except:...
plot_cxctime_custom.py
Source:plot_cxctime_custom.py
...64 :rtype: tuple with selected ticklocs as first element65 """66 locs = ticklocs or TICKLOCS67 for majorLoc, major_kwargs, major_fmt, minorLoc, minor_kwargs in locs:68 plt.xaxis.set_major_locator(majorLoc(**major_kwargs))69 plt.xaxis.set_minor_locator(minorLoc(**minor_kwargs))70 plt.xaxis.set_major_formatter(DateFormatter(major_fmt))71 majorticklocs = plt.xaxis.get_ticklocs()72 if len(majorticklocs) >= 5:73 break74 return ((majorLoc, major_kwargs, major_fmt, minorLoc, minor_kwargs), )75def remake_ticks(ax):76 """Remake the date ticks for the current plot if space is pressed. If '0'77 is pressed then set the date ticks to the maximum possible range.78 """79 ticklocs = set_time_ticks(ax)80 ax.figure.canvas.draw()81 82def plot_cxctime(times, y, fmt='-b', fig=None, ax=None, yerr=None, xerr=None, tz=None,83 state_codes=None, interactive=True, **kwargs):84 """Make a date plot where the X-axis values are in CXC time. If no ``fig``85 value is supplied then the current figure will be used (and created86 automatically if needed). If yerr or xerr is supplied, ``errorbar()`` will be87 called and any additional keyword arguments will be passed to it. Otherwise88 any additional keyword arguments (e.g. ``fmt='b-'``) are passed through to89 the ``plot()`` function. Also see ``errorbar()`` for an explanation of the possible90 forms of *yerr*/*xerr*.91 If the ``state_codes`` keyword argument is provided then the y-axis ticks and92 tick labels will be set accordingly. The ``state_codes`` value must be a list93 of (raw_count, state_code) tuples, and is normally set to ``msid.state_codes``94 for an MSID object from fetch().95 If the ``interactive`` keyword is True (default) then the plot will be redrawn96 at the end and a GUI callback will be created which allows for on-the-fly97 update of the date tick labels when panning and zooming interactively. Set98 this to False to improve the speed when making several plots. This will likely99 require issuing a plt.draw() or fig.canvas.draw() command at the end.100 :param times: CXC time values for x-axis (date)101 :param y: y values102 :param fmt: plot format (default = '-b')103 :param fig: pyplot figure object (optional)104 :param yerr: error on y values, may be [ scalar | N, Nx1, or 2xN array-like ] 105 :param xerr: error on x values in units of DAYS (may be [ scalar | N, Nx1, or 2xN array-like ] )106 :param tz: timezone string107 :param state_codes: list of (raw_count, state_code) tuples108 :param interactive: use plot interactively (default=True, faster if False)109 :param **kwargs: keyword args passed through to ``plot_date()`` or ``errorbar()``110 :rtype: ticklocs, fig, ax = tick locations, figure, and axes object.111 """112 if fig is None:113 fig = pyplot.gcf()114 if ax is None:115 ax = fig.gca()116 if yerr is not None or xerr is not None:117 ax.errorbar(cxctime2plotdate(times), y, yerr=yerr, xerr=xerr, fmt=fmt, **kwargs)118 ax.xaxis_date(tz)119 else:120 ax.plot_date(cxctime2plotdate(np.repeat(times, 2)[1:]), np.repeat(y, 2)[:-1], fmt=fmt, **kwargs)121 ticklocs = set_time_ticks(ax)122 fig.autofmt_xdate()123 if state_codes is not None:124 counts, codes = list(zip(*state_codes))125 ax.yaxis.set_major_locator(FixedLocator(counts))126 ax.yaxis.set_major_formatter(FixedFormatter(codes))127 # If plotting interactively then show the figure and enable interactive resizing128 if interactive and hasattr(fig, 'show'):129 fig.canvas.draw()130 ax.callbacks.connect('xlim_changed', remake_ticks)131 return ticklocs, fig, ax132def cxctime2plotdate(times):133 """134 Convert input CXC time (sec) to the time base required for the matplotlib135 plot_date function (days since start of year 1).136 137 :param times: iterable list of times138 :rtype: plot_date times139 """...
locators_manager.py
Source:locators_manager.py
...54 locators_dict - Dictionary of Locators to be added where each key is the Locator name55 and each value is the corresponding Locator instance56 """57 for x in locators_dict:58 self.add_locator(x, locators_dict[x])59 def add_locator(self, name, locator, locator_type=None):60 """61 Add a single Locator to the list of instances. If not already a Locator instance, 62 it will be instantiated as one.63 @params64 name - name of the Locator65 locator - one of: Locator instance to be added,66 tuple containing (value, locator type)67 String locator value68 locator_type - String type of locator that is being added, as enumerated 69 in selenium.webdriver.common.by:By. one of:70 CSS_SELECTOR (default)71 CLASS_NAME72 ID73 NAME74 LINK_TEXT75 XPATH76 TAG_NAME77 PARTIAL_LINK_TEXT78 """79 if name in self.locators.keys():80 raise Exception('There is an existing locator with the name: %s' % name)81 if isinstance(locator, Locator):82 self.locators[name] = locator83 else:84 if locator_type is None:85 if isinstance(locator, tuple):86 locator_type = locator[0]87 locator = locator[1]88 else:89 locator_type = 'CSS_SELECTOR'90 if not hasattr(By, locator_type):91 raise Exception('Unrecognized locator type: %s' % locator_type)92 self.locators[name] = Locator(self.driver, name, locator, locator_type)93 def find_one(self, locator):94 """95 Find exactly one instance identified by this locator. If multiple elements are found, returns the96 first in the list.97 @params98 locator - one of: String Locator instance name99 String locator definition (using By.CSS_SELECTOR)100 tuple locator containing (value, locator type)101 @returns102 webelement identified by this locator.103 """104 results = self.find(locator)105 if len(results) == 0:106 raise Exception('Locator `%s` not found' % locator)107 return results[0]108 def find(self, locator):109 """110 Find all instances that are identified by this locator111 @params 112 locator - one of: String Locator instance name113 String locator definition (using By.CSS_SELECTOR)114 tuple locator containing (value, locator type)115 @returns116 webelement or list of webelements117 """118 if type(locator) == str:119 # a string definition key was passed in120 if locator in self.locators.keys():121 # we have a definition for this locator key122 #return self.driver.find_elements(getattr(By, self.locators[locator].by), self.locators[locator].locator)123 return self.locators[locator].find()124 else:125 # default to By.CSS_SELECTOR if we don't recognize it126 return self.find(('CSS_SELECTOR', locator))127 else:128 # a tuple definition was passed in129 return self.driver.find_elements(getattr(By, obj[0]), obj[1])130 def find_child(self, webelement, locator):131 """132 Find exactly one instance that is a child of the given webelement, identified by this locator. 133 If multiple elements are found, returns the first in the list.134 @params135 locator - one of: String Locator instance name136 String locator definition (using By.CSS_SELECTOR)137 tuple locator containing (value, locator type)138 @returns139 webelement identified by this locator.140 """141 results = self.find_children(webelement, locator)142 if len(results) == 0:143 raise Exception('Locator `%s` not found' % locator)144 return results[0]145 def find_children(self, webelement, locator):146 """147 Find all instances that are children of a given webelement, identified by this locator.148 @params 149 locator - one of: String Locator instance name150 String locator definition (using By.CSS_SELECTOR)151 tuple locator containing (value, locator type)152 @returns153 webelement or list of webelements154 """155 if type(locator) == str:156 # a string definition key was passed in157 if locator in self.locators.keys():158 # we have a definition for this locator key159 return webelement.find_elements(getattr(By, self.locators[locator].by), self.locators[locator].locator)160 else:161 # default to By.CSS_SELECTOR if we don't recognize it162 return self.find_children(webelement, ('CSS_SELECTOR', locator))163 else:164 # a tuple definition was passed in165 return webelement.find_elements(getattr(By, obj[0]), obj[1])166 def get_locator(self, name):167 """168 Return the raw locator value of a given Locator name169 @params170 name - name of the Locator instance171 @returns172 String value of the locator, regardless of locator type.173 """...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!