Best Python code snippet using lettuce_webdriver_python
web.py
Source:web.py
...69 absolute_file_path = os.path.abspath(file_name)70 driver.find_element_by_xpath("/html/body/div/form/div[1]/input") \71 .send_keys(absolute_file_path)72 # Click to upload73 wait_for_elem(driver, "/html/body/div/form/div[4]/input", By.XPATH, 30).click()74 # Collect upload url75 url = wait_for_elem(driver, "/html/body/div/div[1]/a/img", By.XPATH, 30).get_attribute("src")76 finally:77 driver.close()78 driver.quit()79 return url80def post_forum(string, forum_id, sub_forum_name):81 """82 Post a message on the fourmizzz forum83 :param string: string to post84 :param forum_id: id of the forum to click first85 :param sub_forum_name: name of the forum in which to post86 :return: None87 """88 url = "http://s1.fourmizzz.fr/alliance.php?forum_menu"89 cookies = {'PHPSESSID': get_identifiants_fmz()[-1]}90 options = webdriver.ChromeOptions()91 options.add_argument('--headless')92 options.add_argument("--start-maximized")93 driver = webdriver.Chrome(options=options)94 try:95 driver.get(url)96 for key, value in cookies.items():97 driver.add_cookie({'name': key, 'value': value})98 driver.get(url)99 # Click on the forum name100 wait_for_elem(driver, forum_id, By.CLASS_NAME).click()101 # Click on the subject inside the forum102 wait_for_elem(driver, sub_forum_name, By.LINK_TEXT).click()103 # Click to open answer form104 sleep(5)105 wait_for_elem(driver, "span[style='position:relative;top:-5px", By.CSS_SELECTOR).click()106 # Enter text in the form107 wait_for_elem(driver, "message", By.ID).click()108 driver.find_element_by_id("message").send_keys(string)109 # Click to send the message on the forum110 driver.find_element_by_id("repondre_focus").click()111 finally:112 driver.close()113 driver.quit()114def wait_for_elem(driver, elem, by, tps=15):115 """116 Waits for an elem to appear in a Selenium WebDriver browser117 :param driver: Selenium WebDriver118 :param elem: string of the elem to find119 :param by: find method (XPATH, ID, CLASS_NAME, ...)120 :param tps: time to wait until TimeOut121 :return: WebElement122 """123 for i in range(5):124 try:125 return WebDriverWait(driver, tps).until(ec.presence_of_element_located((by, elem)))126 except StaleElementReferenceException:127 sleep(5)128def get_new_convoys():129 """Returns a dataframe with all the convoys in 'SDC_Convois'"""130 url = "http://s1.fourmizzz.fr/alliance.php?forum_menu"131 cookies = {'PHPSESSID': get_identifiants_fmz()[-1]}132 forum_id = "forum61251.categorie_forum"133 # Opens webDriver134 options = webdriver.ChromeOptions()135 options.add_argument('--headless')136 options.add_argument("--start-maximized")137 driver = webdriver.Chrome(options=options)138 try:139 driver.get(url)140 for key, value in cookies.items():141 driver.add_cookie({'name': key, 'value': value})142 driver.get(url)143 # Click on the forum name144 wait_for_elem(driver, forum_id, By.CLASS_NAME).click()145 sleep(2)146 df_convois = pd.DataFrame(columns=["Date", "Livreur", "Destinataire", "Quantite"])147 # Mark every subforum as read148 i = 2149 while i > 0:150 try:151 # if it's an "important" topic or there are no messages // or it's locked,152 if len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[1]/img")) > 0 \153 or int(wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i+1)+"]/td/div/strong",154 By.XPATH, 2).text) == 0:155 # or (len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr["156 # + str(i) + "]/td[2]/img")) > 0157 # and wait_for_elem(driver,"//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/img", By.XPATH,158 # 2).get_attribute('alt') == "Fermé"):159 i += 2160 continue161 # Click to open the sub forum162 wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/a",163 By.XPATH, 2).click()164 sleep(2) # Wait for the page to load165 # Reset the forum166 driver.get(url)167 # Click on the forum name168 try:169 wait_for_elem(driver, forum_id, By.CLASS_NAME).click()170 except TimeoutException:171 forum_id = forum_id.replace("categorie_forum", "ligne_paire")172 wait_for_elem(driver, forum_id, By.CLASS_NAME).click()173 sleep(1)174 # Waits if the element didn't load yet175 except (StaleElementReferenceException, IndexError):176 sleep(0.5)177 # Leave the loop if there is no more sub forum to read178 except TimeoutException:179 break180 # Go to the next sub forum181 else:182 i += 2183 # Check every sub forum for convoys184 i = 2185 while i > 0:186 try:187 # if it's an "important" topic or there are no messages // or it's locked,188 if len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[1]/img")) > 0 \189 or int(wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i+1)+"]/td/div/strong",190 By.XPATH, 2).text) == 0:191 # or (len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr["192 # + str(i) + "]/td[2]/img")) > 0193 # and wait_for_elem(driver,"//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/img", By.XPATH,194 # 2).get_attribute('alt') == "Fermé"):195 i += 2196 continue197 topic_name = wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/a",198 By.XPATH, 2).text199 # Find the name of the requester and the amount requested200 try:201 destinataire, total_amount = topic_name.split(" - ")[1:3]202 except ValueError:203 continue204 total_amount = int(EngNumber(total_amount.replace(" ", "").replace("\u202f", "")))205 # Click to open the sub forum206 wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/a",207 By.XPATH, 2).click()208 sleep(2) # Wait for the page to load209 # Read every message inside the forum210 j = 2211 while j > 0:212 try:213 # Read the date of the convoy214 annee = datetime.today().year215 # if it's a new message, adapt the Xpath216 if len(driver.find_elements_by_xpath("//*[@id='forum']/div["+str(j+1)+"]/img")) > 0:217 date = wait_for_elem(driver, "//*[@id='forum']/div["+str(j+1)+"]/span[2]", By.XPATH, 1)\218 .text.split()219 else:220 date = wait_for_elem(driver, "//*[@id='forum']/div["+str(j+1)+"]/span", By.XPATH, 1)\221 .text.split()222 if len(date) == 5:223 annee = int(date[2])224 del date[2]225 mois = ["janv.", "févr.", "mars", "avril", "mai", "juin",226 "juil.", "août", "sept.", "oct.", "nov.", "déc."]227 date = datetime(annee, mois.index(date[1])+1, int(date[0]),228 *(int(elem) for elem in date[3].split("h")))229 if date > datetime.today():230 date = datetime(date.year-1, date.month, date.day, date.hour, date.minute)231 # Read the sender232 livreur = wait_for_elem(driver, "//*[@id='forum']/div["+str(j+1)+"]/a", By.XPATH, 2).text233 # Read the quantity234 quantite = wait_for_elem(driver, "//*[@id='forum']/div["+str(j+2)+"]", By.XPATH, 2).text235 try:236 quantite = [int(match.replace("mat", "").replace("à ", "").replace("et", ""))237 for match in re.findall("et[0-9]+mat|et[0-9]+à ", quantite.replace(" ", ""))]238 except AttributeError:239 log("Web", "Convoy entry incorrect",240 "{} {} {} '"'{}'"'".format(date, livreur, destinataire, quantite))241 else:242 # If everything is right, append the convoy to the dataframe243 if len(df_convois.index) > 0 \244 and df_convois.at[df_convois.index[-1], "Date"].minute == date.minute:245 date += timedelta(seconds=df_convois.at[df_convois.index[-1], "Date"].second+1)246 for s, match in enumerate(quantite):247 df_convois = df_convois.append(pd.DataFrame({"Date": [date + timedelta(seconds=s)],248 "Livreur": [livreur],249 "Destinataire": [destinataire],250 "Quantite": [match]}),251 ignore_index=True)252 total_amount -= match253 # Leave the loop if there is no more message to read254 except TimeoutException:255 # Calculate the remaining amount if needed256 if wait_for_elem(driver, "//*[@id='forum']/div["+str(j-1)+"]/a", By.XPATH, 2).text \257 != get_identifiants_fmz()[0] \258 or len(quantite) > 0:259 convoy_link = get_convoy_link(destinataire)260 post_forum("[url="+convoy_link+"]"+destinataire+"[/url]\n\n"261 + "Reste: "+'{:,}'.format(total_amount).replace(",", " "),262 forum_id, topic_name)263 log("Forum", "Convoy countdown update", destinataire+"'s convoys updated")264 if total_amount <= 0:265 send_pm(get_identifiants_fmz()[0], "[Convoys finished]",266 destinataire+"'s convoys finished, activation requested")267 break268 # Go to the next message269 else:270 j += 2271 # Reset the forum272 driver.get(url)273 # Click on the forum name274 wait_for_elem(driver, forum_id, By.CLASS_NAME).click()275 sleep(1)276 # Waits if the element didn't load yet277 except (StaleElementReferenceException, IndexError):278 sleep(0.5)279 # Leave the loop if there is no more sub forum to read280 except TimeoutException:281 break282 # Go to the next sub forum283 else:284 i += 2285 finally:286 driver.close()287 driver.quit()288 # Reset the indices just in case289 df_convois.reset_index(inplace=True, drop=True)290 return df_convois291def get_convoy_link(player_name):292 url = "http://s1.fourmizzz.fr/Membre.php?Pseudo=" + player_name293 cookies = {'PHPSESSID': get_identifiants_fmz()[-1]}294 options = webdriver.ChromeOptions()295 options.add_argument('--headless')296 options.add_argument("--start-maximized")297 driver = webdriver.Chrome(options=options)298 try:299 driver.get(url)300 for key, value in cookies.items():301 driver.add_cookie({'name': key, 'value': value})302 driver.get(url)303 # get convoy link304 link = wait_for_elem(driver, "/html/body/div[4]/center/div[2]/table/tbody/tr/td[1]/a[1]", By.XPATH, 5)\305 .get_attribute('href')306 finally:307 driver.close()308 driver.quit()309 return link310def send_pm(player_name=None, subject="", text="No text"):311 if player_name is None:312 player_name = get_identifiants_fmz()[0]313 url = "http://s1.fourmizzz.fr/messagerie.php?defaut=Ecrire&destinataire=" + player_name314 cookies = {'PHPSESSID': get_identifiants_fmz()[-1]}315 options = webdriver.ChromeOptions()316 options.add_argument('--headless')317 options.add_argument("--start-maximized")318 driver = webdriver.Chrome(options=options)319 try:320 driver.get(url)321 for key, value in cookies.items():322 driver.add_cookie({'name': key, 'value': value})323 driver.get(url)324 # write object325 wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[2]/span/input", By.XPATH, 5).click()326 wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[2]/span/input", By.XPATH, 5)\327 .send_keys(subject)328 # write main text329 wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[3]/span/textarea", By.XPATH, 5).click()330 wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[3]/span/textarea", By.XPATH, 5)\331 .send_keys(text)332 # send pm333 wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[4]/span[1]/input", By.XPATH, 50).click()334 finally:335 driver.close()336 driver.quit()337 log("Web", "Mp sent", "Mp sent to " + player_name)338def get_identifiants_fmz():339 with open("files/identifiants_fmz.txt") as file:340 identifiants = file.readlines()341 identifiants = [elem.strip() for elem in identifiants]342 return identifiants343def reconnect():344 pseudo, mdp, cook = get_identifiants_fmz()345 url = "http://s1.fourmizzz.fr"346 cookies = {'PHPSESSID': cook}347 options = webdriver.ChromeOptions()348 options.add_argument('--headless')349 options.add_argument("--start-maximized")350 driver = webdriver.Chrome(options=options)351 try:352 driver.get(url)353 for key, value in cookies.items():354 driver.add_cookie({'name': key, 'value': value})355 driver.get(url)356 wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[2]/td[2]/input", By.XPATH).click()357 wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[2]/td[2]/input", By.XPATH).send_keys(pseudo)358 wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[3]/td[2]/input", By.XPATH).click()359 wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[3]/td[2]/input", By.XPATH).send_keys(mdp)360 wait_for_elem(driver, "//*[@id='loginForm']/input[2]", By.XPATH).click()361 except TimeoutException:362 log("Web", "Reconnection", "Reconnection failed")363 finally:364 driver.close()...
main.py
Source:main.py
...40 time.sleep(round_time)41 return wrapper42 return decorator43@wait_for()44def wait_for_elem(selector):45 return browser.find_element(selector[0], selector[1])46@wait_for()47def wait_for_attribute(elem, attr, allow_none = False):48 attrVal = elem.get_attribute(attr)49 if not allow_none and attrVal is None:50 raise Exception('val can\'t be None.')51 return attrVal52def switch_frame(frameSelector):53 elem = wait_for_elem(frameSelector)54 browser.switch_to.frame(elem)55def get_slide_distance(slide, target):56 # slide_img = slide_libs.url2image(slide.get_attribute("src"))57 # target_img = slide_libs.url2image(target.get_attribute("src"))58 slide_img = slide_libs.url2image(wait_for_attribute(slide, "src"))59 target_img = slide_libs.url2image(wait_for_attribute(target, "src"))60 61 position = slide_libs.check_position(slide_img, target_img)62 t_size = target.size63 t_loc = target.location64 s_loc = slide.location65 # slide_libs.show(slide_img, target_img, position)66 67 return t_loc['x'] +t_size['width'] * position['x'] - s_loc['x']68# å°ä¸ä¸ªæ»å¨è·ç¦» æ为 å¤ä¸ªéæ¸åå°ç æ»å¨è·ç¦»69def fuck_distance(rest_dis, dis_list = None):70 if dis_list is None:71 dis_list = []72 73 this_dis = rest_dis / 2 + random.uniform(0, 30.0)74 dis_list.append(this_dis)75 rest_dis = rest_dis - this_dis76 if rest_dis > 0:77 return fuck_distance(rest_dis, dis_list=dis_list)78 if rest_dis < 0:79 dis_list[-1] = dis_list[-1] + rest_dis + random.uniform(-1.0, 1.0)80 return dis_list81options = Options()82options.headless = OPTS_HEADLESS83browser = webdriver.Firefox(executable_path = FIREFOX_DRIVER_PATH, options = options)84browser.set_page_load_timeout(5.0)85print("opening home page.")86start = time.perf_counter()87try:88 browser.get(home_url)89except TimeoutException as err:90 print('timeout')91switch_frame(account_iframe_selector)92wait_for_elem(account_tab_selector).click()93wait_for_elem(username_input_selector).send_keys(USERNAME)94wait_for_elem(password_input_selector).send_keys(PASSWORD)95wait_for_elem(login_button_selector).click()96switch_frame(tcaptcha_iframe_selector)97slide_elem = wait_for_elem(slide_img_selector)98target_elem = wait_for_elem(target_img_selector)99dis = get_slide_distance(slide_elem, target_elem)100action = ActionChains(browser)101action.click_and_hold(slide_elem).perform()102action.move_by_offset(dis, 0).perform()103# print(dis)104# dis_list = fuck_distance(dis)105# print(dis_list)106# move_dis = 0107# for dis_item in dis_list:108# move_dis += dis_item109# print('move: ' + str(move_dis))110# action.move_to_element_with_offset(slide_elem, move_dis, random.uniform(0, 1)).perform()111# print('rest dis: ' + str(get_slide_distance(slide_elem, target_elem)))112# time.sleep(random.uniform(0.5, 1))...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!