Best Python code snippet using playwright-python
book.py
Source:book.py
...78 otp_form = load('/html/body/app-root/ion-app/ion-router-outlet/app-login/ion-content/div/ion-grid/ion-row/ion-col/ion-grid/ion-row/ion-col/ion-grid/form/ion-row/ion-col[2]/ion-item/mat-form-field/div/div[1]/div/input')79 otp_form.clear()80 otp_form.send_keys(OTP)81 load('/html/body/app-root/ion-app/ion-router-outlet/app-login/ion-content/div/ion-grid/ion-row/ion-col/ion-grid/ion-row/ion-col/ion-grid/form/ion-row/ion-col[3]/div/ion-button').click()82 wait_for_url('https://selfregistration.cowin.gov.in/dashboard', duration=180)83 time.sleep(delays['load_dashboard'])84 driver.execute_script('document.querySelector("#main-content > app-beneficiary-dashboard > ion-content > div > div > ion-grid > ion-row > ion-col > ion-grid.beneficiary-box.md.hydrated > ion-row:nth-child(' + str(beneficiary_id+1) + ') > ion-col > ion-grid > ion-row.dose-data.md.hydrated > ion-col:nth-child(2) > ul > li > a").scrollIntoView()')85 86 #Another driver.execute_script to scroll into view the confirmation button, if need be.87 schedule_button = load('/html/body/app-root/ion-app/ion-router-outlet/app-beneficiary-dashboard/ion-content/div/div/ion-grid/ion-row/ion-col/ion-grid[1]/ion-row[' + str(beneficiary_id+1) + ']/ion-col/ion-grid/ion-row[4]/ion-col[2]/ul/li/a')88 driver.execute_script("arguments[0].click();", schedule_button)89 try:90 #driver.execute_script(f'document.querySelector("#main-content > app-beneficiary-dashboard > ion-content > div > div > ion-grid > ion-row > ion-col > ion-grid.beneficiary-box.md.hydrated > ion-row:nth-child({int(total)+3}) > ion-col > div > div:nth-child(2) > div > ion-button".scrollIntoView()')91 confirm_button = load(f'/html/body/app-root/ion-app/ion-router-outlet/app-beneficiary-dashboard/ion-content/div/div/ion-grid/ion-row/ion-col/ion-grid[1]/ion-row[{int(total)+3}]/ion-col/div/div[2]/div/ion-button')92 driver.execute_script("arguments[0].click();", confirm_button)93 except:94 pass95 return 196 except Exception as e:97 print(e)98 return -199 100def search(driver, load, click, wait_for_url):101 time_now = datetime.now().time()102 hour = int(str(time_now).split(':')[0])103 start_date = 1104 if hour > 16:105 start_date = 2106 try:107 capture_time = time.strftime("%I:%M:%S %p", time.localtime())108 print(today, capture_time)109 print()110 111 112 print('Vaccination Center'+((40-len('Vaccination Center'))*' '), 'Pincode', ' '*2, 'Vaccine Type'+' '*4, 'Date'+((15-len('Date'))*' '), 'Status')113 print("-"*115)114 print("-"*115)115 for pincode in pincodes:116 pincode_box = load('#mat-input-0', options='css')117 pincode_box.clear()118 pincode_box.send_keys(pincode)119 load('#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col:nth-child(2) > form > ion-grid > ion-row > ion-col.col-padding.ion-text-start.ng-star-inserted.md.hydrated > ion-button', options='css').click()120 if visual_filter:121 driver.execute_script('document.querySelector("#c1").click()')122 time.sleep(delays['under45_filter'])123 #print("18+ Filter enabled")124 centre_name = None125 try:126 centre_name = load("#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col:nth-child(2) > form > ion-grid > ion-row > ion-col.col-padding.matlistingblock.ng-star-inserted.md.hydrated > div > div > mat-selection-list > div:nth-child(1) > mat-list-option > div > div.mat-list-text > ion-row > ion-col.main-slider-wrap.md.hydrated > div > h5", options='css', duration=delays['empty_pincode']).text127 except:128 #print("No 18+ centres in this pincode.")129 continue130 ROWS = []131 for row in range(1,8):132 try:133 centre_name = driver.find_element_by_css_selector("#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col:nth-child(2) > form > ion-grid > ion-row > ion-col.col-padding.matlistingblock.ng-star-inserted.md.hydrated > div > div > mat-selection-list > div:nth-child(" + str(row) + ") > mat-list-option > div > div.mat-list-text > ion-row > ion-col.main-slider-wrap.md.hydrated > div > h5").text134 #print(centre_name.lower())135 if selective:136 for centre_keyword in centre_keywords:137 if centre_keyword.lower() in centre_name.lower():138 ROWS.append(row)139 else:140 ROWS.append(row)141 except:142 break143 column = 2144 #print("Obtained centres. The indices are:", ROWS)145 146 for row in ROWS:147 for column in range(start_date,start_date+3):148 try:149 type1 = "#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col:nth-child(2) > form > ion-grid > ion-row > ion-col.col-padding.matlistingblock.ng-star-inserted.md.hydrated > div > div > mat-selection-list > div:nth-child(" + str(row) + ") > mat-list-option > div > div.mat-list-text > ion-row > ion-col.slot-available-main.col-padding.md.hydrated > ul > li:nth-child(" + str(column) + ") > div > div > {}"150 vaccines = load(type1.format("a"), options='css')151 if vaccines.text == 'Booked' or vaccines.text == 'NA':152 centre_name = driver.find_element_by_css_selector("#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col:nth-child(2) > form > ion-grid > ion-row > ion-col.col-padding.matlistingblock.ng-star-inserted.md.hydrated > div > div > mat-selection-list > div:nth-child(" + str(row) + ") > mat-list-option > div > div.mat-list-text > ion-row > ion-col.main-slider-wrap.md.hydrated > div > h5").text153 centre_name += (40-len(centre_name))*' '154 vaccine_text = vaccines.text155 if vaccine_text == 'Booked':156 vaccine_type = driver.find_element_by_css_selector(type1.format("div.vaccine-cnt > h5")).text157 age_limit = driver.find_element_by_css_selector(type1.format("div.ng-star-inserted > span")).text158 if '18' not in age_limit:159 continue 160 else:161 vaccine_type = 'Unknown'162 continue163 vaccine_type += (16-len(vaccine_type))*' '164 print(centre_name, pincode, ' '*3, vaccine_type, str(int(today[:2])+column-1).zfill(2)+today[2:]+' '*5, vaccine_text)165 """if column == start_date:166 print(centre_name, pincode, ' '*3, vaccine_type, str(int(today[:2])+column-1).zfill(2)+today[2:]+' '*5, vaccine_text)167 else:168 print(centre_name, ' '*6, ' '*3, vaccine_type, str(int(today[:2])+column-1).zfill(2)+today[2:]+' '*5, vaccine_text)"""169 print("-"*115)170 continue171 if int(vaccines.text) >= 1:172 try:173 age_limit = driver.find_element_by_css_selector(type1.format("div.ng-star-inserted > span")).text174 vaccine_type = driver.find_element_by_css_selector(type1.format("div.vaccine-cnt > h5")).text 175 print(age_limit)176 if '45' in age_limit:177 continue178 elif '18' not in age_limit:179 continue180 except Exception as e:181 print(e)182 continue 183 184 vaccines.click()185 pygame.mixer.music.play()186 #winsound.Beep(4400, 2500) 187 except Exception as e:188 print("Double Slot Error\n")189 print(e)190 print()191 try:192 for subcolumn in [1,2]:193 type2 = "#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col:nth-child(2) > form > ion-grid > ion-row > ion-col.col-padding.matlistingblock.ng-star-inserted.md.hydrated > div > div > mat-selection-list > div:nth-child(" + str(row) + ") > mat-list-option > div > div.mat-list-text > ion-row > ion-col.slot-available-main.col-padding.md.hydrated > ul > li:nth-child(" + str(column) + ") > div:nth-child(" + str(subcolumn) +") > div > a"194 vaccines = load(type2, options='css')195 if vaccines.text == 'Booked' or vaccines.text == 'NA' or vaccines.text == '0':196 continue197 vaccines.click()198 pygame.mixer.music.play()199 except Exception as e:200 print('FATAL ERROR')201 print(e)202 return203 try:204 load("#main-content > app-appointment-table > ion-content > div > div > ion-grid > ion-row > ion-col > ion-grid > ion-row > ion-col.register-header.md.hydrated > div > ion-button.time-slot.ng-star-inserted.md.button.button-solid.ion-activatable.ion-focusable.hydrated.activeBtn", options='css').click()205 except:206 print("CHOOSE TIMESLOT TOO!")207 input("Press Enter to resume.")208 209 #time.sleep(1)210 except Exception as e:211 print(e)212 return -1213def loopscan(driver, load, click, wait_for_url):214 driver.get("https://selfregistration.cowin.gov.in/")215 login(driver, load, click, wait_for_url)216 count = 0217 ecounter = 0218 while True:219 if (search(driver, load, click, wait_for_url) == -1):220 ecounter += 1221 if (ecounter > 3):222 print("Rate limit reached. Rebooting.")223 #driver.quit()224 break225 if count % 15 == 0:226 driver.refresh()227 if (driver.current_url == "https://selfregistration.cowin.gov.in/"):228 requests.post("https://cdn-api.co-vin.in/api/v2/auth/public/generateOTP", data = {229 "mobile": MOBILE230 })231 time.sleep(2)232 count = 0233 count += 1234 print(f"\n\n\nCOUNT: {count}\n\n\n")235def main():236 driver = selenium_utils.make_driver(profile=3)237 load = selenium_utils.load(driver)238 click = selenium_utils.click(driver)239 wait_for_url = selenium_utils.wait_for_url(driver)240 while True:241 loopscan(driver, load, click, wait_for_url)242print(f"Perseverance v{VERSION}")...
chegging.py
Source:chegging.py
...63 count = 064 prev = -165 now = 066 self.login()67 self.wait_for_url(Chegger.CHEGG_LOGIN)68 logging.info("Logged in successfully")69 logging.info("Redirecting to "+Chegger.CHEGG_EXPERT_QA+" ...")70 self.driver.get(Chegger.CHEGG_EXPERT_QA)71 self.wait_for_url(Chegger.CHEGG_EXPERT_QA)72 logging.info("Starting to answer")73 self.start_answering()74 while True:75 if self.is_current_url(Chegger.CHEGG_EXPERT_QA):76 self.start_answering()77 self.wait_for_url(Chegger.CHEGG_QA)78 now = self.get_element("(//div[@data-test-id='skipped']//span)[2]").text79 80 _question = self.question()81 _reply = self.categorizer(_question)82 if _reply:83 try:84 playsound.playsound("boss.mp3")85 except:86 pass87 _input = input("program paused(press enter to continue)")88 _status = input("Have you answered the question(y/n)? ")89 if _status.lower() in ("y","yeah","yes","yep"):90 pass91 else:92 self.skip()93 else:94 self.skip()95 if count==Chegger.PAUSE_FOR:96 _status = input("Would you like to continue(y/n)? ")97 if _status in ("y","yeah","yes","yep"):98 count = 099 pass100 else:101 logging.info("Stopping the program...")102 break103 count += 1104 105 def login(self):106 logging.info("Logging into "+Chegger.CHEGG_LOGIN+ " ...")107 self.driver.get(Chegger.CHEGG_LOGIN)108 _username = self.get_element("//input[@id='emailForSignIn']")109 _password = self.get_element("//input[@id='passwordForSignIn']")110 _submit = self.get_element("//button[@name='login']")111 logging.info("\t* Filled email field with "+self.email)112 _username.send_keys(self.email)113 time.sleep(1)114 logging.info("\t* Filled password field with "+self.pswd)115 _password.send_keys(self.pswd)116 logging.info("\t* Submittiing form...")117 self.driver.execute_script("arguments[0].click();", _submit)118 logging.info("Logged in successfully")119 def start_answering(self):120 logging.info("Starting to answer questions...")121 _start_answering = self.get_element("//button[text()='Start answering questions']")122 self.driver.execute_script("arguments[0].click();", _start_answering)123 def skip(self): 124 self.wait_for_url(Chegger.CHEGG_QA) 125 self.skipped += 1126 _question = self.get_element("//div[@data-test-id='question']")127 logging.info("Skipping question no "+str(self.skipped))128 _skip = self.get_element("//span[text()='Skip']")129 try:130 self.driver.execute_script("arguments[0].click();", _skip)131 except:132 time.sleep(1)133 self.driver.execute_script("arguments[0].click();", _skip)134 135 _i_dont_have_knowledge = self.get_element("//label[contains(text(),'I don')]")136 self.driver.execute_script("arguments[0].click();", _i_dont_have_knowledge)137 _topic = self.get_element("//span[contains(text(),'What topic should it be?')]")138 self.driver.execute_script("arguments[0].click();", _topic)139 logging.info("Skipping as Other Computer Science ...")140 _category = self.get_element("//li[contains(text(),'Other Computer Science')]")141 self.driver.execute_script("arguments[0].click();", _category)142 logging.info("Submitting response...")143 _submit = self.get_element("//span[text()='Submit']")144 self.driver.execute_script("arguments[0].click();", _submit)145 logging.info("Skipped question successfully ...")146 while _question == self.get_element("//div[@data-test-id='question']"):147 time.sleep(0.5)148 def question(self):149 self.wait_for_url(Chegger.CHEGG_QA)150 logging.info("Started to fetch question ...")151 _question = self.get_element("//div[@data-test-id='question']")152 _paragraphs = _question.find_elements("xpath","//p")153 _text = ""154 _images = _question.find_elements("xpath","//img")155 _urls = list()156 logging.info("\t* Getting urls of images")157 for img in _images:158 _urls.append(img.get_attribute("src"))159 logging.info("\t* "+str(len(_urls))+" images are found in question")160 for para in _paragraphs:161 _text += para.text+" "162 logging.info("Converting images to text using tesseract ...")163 for url in _urls:164 name=url.split("/")[-1]165 if "." not in name:166 continue167 image = open("images\\"+name, "wb")168 try:169 image.write(requests.get(url, allow_redirects=True).content)170 except:171 continue172 try:173 _text += pytesseract.image_to_string(Image.open("images\\"+name)) + " "174 except:175 pass176 image.close()177 logging.info("Question extracted successfully from images and user added text ...")178 logging.info(f"Question\n{_text}")179 return _text180 def answer(self):181 self.wait_for_url(Chegger.CHEGG_QA)182 logging.info("Answering to question ...")183 _answer = self.get_element("//span[text()='Answer']")184 self.driver.execute_script("arguments[0].click();", _answer)185 @classmethod #this method you can modify as your wish it basically searches for keywords in a given-question-as-text186 def categorizer(cls, question): 187 logging.info("Searching for key words in question ...")188 _flag = 0189 words = cls.KEYWORDS_FOR_QUESTIONS_YOU_ANSWER190 question = question.lower()191 for i in set(question):192 if ord(i) not in [*range(65,91),*range(97,123),*range(48,58)]:193 question=question.replace(i," ")194 # _flag = len(re.findall("|".join(words),question.lower()))195 recognized = []196 for i in question.split():197 for j in words:198 if j in i:199 if j not in recognized:200 recognized.append(j)201 print("\t\t* "+j)202 _flag += 1203 mul_flag = len(re.findall("[Qq]uestion[.]? *[no]? *[0-9a-zA-Z]* *[.)]?|[Qq][.]? *[no]? *[0-9a-zA-Z]* *[.)]?", question))204 logging.info("Searching for key words in question for not answering ...")205 words = cls.KEYWORDS_FOR_QUESTIONS_YOU_AVOID206 _flag_avoid=0207 recognized = []208 for i in question.split():209 for j in words:210 if j in i:211 if j not in recognized:212 recognized.append(j)213 print("\t\t* "+j)214 _flag_avoid += 1215 if _flag==0:216 logging.info("No keywords found")217 if len(re.findall("[0-9a-zA-Z]",question)) <= 600:218 logging.info("\t____small_question____")219 _flag = 1220 if mul_flag>=2:221 logging.info("\t____multiple_choice_question____")222 _flag = 1223 if _flag_avoid:224 _flag = 0225 return _flag226 def is_current_url(self, url):227 u1 = urlparse(url)228 u2 = urlparse(self.driver.current_url)229 _flag = True230 for i in range(3):231 if u1[i]!=u2[i]:232 _flag = False233 return _flag234 def get_element(self, path):235 element = ""236 try:237 element = self.wait.until(238 EC.presence_of_element_located(("xpath", path))239 )240 finally:241 return element242 def wait_for_url(self, url):243 logging.info("If the url is not loading please load it manually")244 logging.info("Until then program waits...")245 self.wait.until(EC.url_to_be(url))246 247if __name__=="__main__":248 chegger = Chegger("email@gmail.com", "password")...
test_home.py
Source:test_home.py
...32 assert_expectations()33 def test_machine_learning_page(self):34 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)35 self.home_page.click_menu_item(MenuItems.MACHINE_LEARNING.values[0])36 self.home_page.page.wait_for_url(MenuItems.MACHINE_LEARNING.values[1])37 assert self.home_page.page.url == MenuItems.MACHINE_LEARNING.values[1], \38 f'actual : {self.home_page.page.url} \n' \39 f'expected : {MenuItems.MACHINE_LEARNING.values[1]}'40 def test_digital_software_development_page(self):41 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)42 self.home_page.click_menu_item(MenuItems.DIGITAL_SOFTWARE_DEVELOPMENT.values[0])43 self.home_page.page.wait_for_url(MenuItems.DIGITAL_SOFTWARE_DEVELOPMENT.values[1])44 assert self.home_page.page.url == MenuItems.DIGITAL_SOFTWARE_DEVELOPMENT.values[1], \45 f'actual : {self.home_page.page.url} \n' \46 f'expected : {MenuItems.DIGITAL_SOFTWARE_DEVELOPMENT.values[1]}'47 def test_user_experience_page(self):48 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)49 self.home_page.click_menu_item(MenuItems.USER_EXPERIENCE.values[0])50 self.home_page.page.wait_for_url(MenuItems.USER_EXPERIENCE.values[1])51 assert self.home_page.page.url == MenuItems.USER_EXPERIENCE.values[1], \52 f'actual : {self.home_page.page.url} \n' \53 f'expected : {MenuItems.USER_EXPERIENCE.values[1]}'54 def test_culture_page(self):55 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)56 self.home_page.click_menu_item(MenuItems.CULTURE.values[0])57 self.home_page.page.wait_for_url(MenuItems.CULTURE.values[1])58 assert self.home_page.page.url == MenuItems.CULTURE.values[1], \59 f'actual : {self.home_page.page.url} \n' \60 f'expected : {MenuItems.CULTURE.values[1]}'61 def test_our_work_page(self):62 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)63 self.home_page.click_menu_item(MenuItems.OUR_WORK.values[0])64 self.home_page.page.wait_for_url(MenuItems.OUR_WORK.values[1])65 assert self.home_page.page.url == MenuItems.OUR_WORK.values[1], \66 f'actual : {self.home_page.page.url} \n' \67 f'expected : {MenuItems.OUR_WORK.values[1]}'68 def test_articles_page(self):69 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)70 self.home_page.click_menu_item(MenuItems.ARTICLES.values[0])71 self.home_page.page.wait_for_url(MenuItems.ARTICLES.values[1])72 assert self.home_page.page.url == MenuItems.ARTICLES.values[1], \73 f'actual : {self.home_page.page.url} \n' \74 f'expected : {MenuItems.ARTICLES.values[1]}'75 def test_engagement_models_page(self):76 self.home_page.click_menu_header_button(MenuCloseHeader.MENU.value)77 self.home_page.click_menu_item(MenuItems.ENGAGEMENT_MODELS.values[0])78 self.home_page.page.wait_for_url(MenuItems.ENGAGEMENT_MODELS.values[1])79 assert self.home_page.page.url == MenuItems.ENGAGEMENT_MODELS.values[1], \80 f'actual : {self.home_page.page.url} \n' \...
entrypoint.py
Source:entrypoint.py
...54class RancherBootstrapper:55 project_id = None56 stack_id = None57 registrationUrl = None58 def wait_for_url(self, url):59 logging.info("Waiting for %s", url)60 s.get(url)61 def create_environment(self):62 url = "%s/v2-beta/projects" % (BASE_URL)63 matching_envs = filter((lambda (x): x['name'] == 'test'), s.get(url).json()['data'])64 if len(matching_envs) > 0:65 self.project_id = matching_envs[0]['id']66 logging.info("Found env %s", self.project_id)67 return68 payload = { 'name': 'test' }69 r = s.post(url, json=payload)70 self.project_id = r.json()['id']71 logging.info("Created env %s", self.project_id)72 def create_stack(self):73 url = "%s/v2-beta/projects/%s/stacks" % (BASE_URL, self.project_id)74 json = s.get(url).json()75 logging.debug("%s", json)76 matching_stacks = filter((lambda (x): x['name'] == 'test'), json['data'])77 if len(matching_stacks) > 0:78 self.stack_id = matching_stacks[0]['id']79 logging.info("Found stack %s", self.stack_id)80 return81 payload = { 'name': 'test', 'dockerCompose': DOCKER_COMPOSE, 'startOnCreate': True }82 r = s.post(url, json=payload)83 self.stack_id = r.json()['id']84 logging.debug("%s", r.json())85 logging.info("Created stack %s", self.stack_id)86 def create_job(self):87 url = "%s/createItem?name=test" % (JENKINS_URL)88 config = XML_TEMPLATE.format(project_id=self.project_id, host_ip=HOST_IP)89 headers = {'Content-Type': 'application/xml'}90 r = s.post(url, data=config, headers=headers)91 logging.debug("%s", r.text)92 def bootstrap(self):93 self.wait_for_url(BASE_URL)94 self.wait_for_url(JENKINS_URL)95 self.create_environment()96 self.create_stack()97 self.create_job()98 self.set_server_endpoint()99 self.get_registration_tokens()100 self.run_agent()101 def set_server_endpoint(self):102 url = "%s/v2-beta/settings/api.host" % (BASE_URL)103 payload = { 'value': ('%s:8080' % (HOST_IP))}104 r = s.put(url, json=payload)105 logging.debug('%s', r.json())106 def get_registration_tokens(self):107 url = "%s/v2-beta/projects/%s/registrationTokens" % (BASE_URL, self.project_id)108 s.post(url)...
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!!