def config_bt_bot(driver, webdriver, chunk, bot): h = MadHatterBot() sleep(1) chunk.reset_index(drop=True, inplace=True) clones = [] for ii in range(len(chunk)): name = F"{bot.priceMarket.primaryCurrency}|{bot.priceMarket.secondaryCurrency},#{ii}" clone = h.clone_bot_for_bt2(bot, str(name)) print(clone.name, 'Clonr NAME') config = h.apply_config_to_madhatter_bot(clone, chunk, ii) clones.append(clone) element = WebDriverWait(driver, 120).until( EC.presence_of_element_located(driver, By.XPATH("//*[@data-guid=]"))) try: driver.find_element_by_id("botRemoteStartCustom").click() except: driver.find_element_by_id("botRemoteWindow").click() finally: driver.find_element_by_id("botRemoteStartCustom").click() try: driver.find_element_by_link_text('Close').click() except: pass bt_over = f"The backtest of bot {name} has finished" element = WebDriverWait(driver, 120).until( EC.text_to_be_present_in_element((By.XPATH("//", bt_over)))) chunk['roi'][ii] = h.return_bot(clone.guid).roi h.delete_temp_bot(clone) return chunk
def select_return_date_for_journey(self, pick_up_date): try: pick_up_date = pick_up_date.strptime("%d %B %Y") return_date = (pick_up_date + datetime.timedelta(days=7)).strftime("%d %B %Y") date = pick_up_date.split(" ")[0] month = pick_up_date.split(" ")[1] year = pick_up_date.split(" ")[2] month_year = month + year WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located(By.XPATH(INPUT_DATE))) self.driver.find_element_by_xpath(INPUT_DATE).click() WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located( By.XPATH(WEBELEMENt_INPUT_CALENDER_WIDGET))) self.driver.find_element_by_xpath( WEBELEMENT_MONTH_DROPDOWN.format(month_year)).click() calendar_rows = self.driver.find_elements_by_xpath( WEBELEMET_CALENDAR_ROWS) for row in calendar_rows: calendar_columns = self.driver.find_elements_by_xpath( row.find_elements_by_xpath("./td/a")) for col in calendar_columns: col_value = col.text if col_value == date: col.click() return return_date except Exception as err: logging.error("issue in clicking return date")
def selct_pick_up_date_fpr_journey(self): """ Method to select pickupdate from budget page :param date: :return: """ try: WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located(By.XPATH(INPUT_DATE))) self.driver.find_element_by_xpath(INPUT_DATE).click() WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located( By.XPATH(WEBELEMENt_INPUT_CALENDER_WIDGET))) current_date = datetime.date.today() pick_up_date = (current_date + datetime.timedelta(days=7)).strftime("%d %B %Y") date = pick_up_date.split(" ")[0] month = pick_up_date.split(" ")[1] year = pick_up_date.split(" ")[2] month_year = month + year self.driver.find_element_by_xpath( WEBELEMENT_MONTH_DROPDOWN.format(month_year)).click() calendar_rows = self.driver.find_elements_by_xpath( WEBELEMET_CALENDAR_ROWS) for row in calendar_rows: calendar_columns = self.driver.find_elements_by_xpath( row.find_elements_by_xpath("./td/a")) for col in calendar_columns: col_value = col.text if col_value == date: col.click() return pick_up_date except Exception as err: logging.error("Issue in selecting pickup date")
def _get_booking_status(self, weekday_index, time_index): xpath = self._get_xpath_from_datetime(weekday_index, time_index) status_text = None if self.driver.find_elements(By.XPATH(xpath + '/a')).__sizeof__() != 0: status = self._wait_and_select_element_by_xpath(xpath + '/a') elif self.driver.find_elements(By.XPATH(xpath + '/span')).__sizeof__() != 0: status = self._wait_and_select_element_by_xpath(xpath + '/span') if status: status_text = status.text return status_text
def testSchedule(self): assert self.driver.find_element_by_id('tab_icon').is_displayed() self.driver.swipe(516, 1262, 564, 1310) self.driver.scroll("7, 1233, 713, 1233") self.driver.swipe( "start_x'=516, 'start_y'=1262, 'end_x'=564, 'end_y'=1310, 10") self.driver.find_element_by_id('tab_icon').click() self.driver.find_element_by_xpath( "//androidx.appcompat.app.ActionBar.Tab[@content-desc='SCHEDULE']/android.view.ViewGroup[@bounds='[516,1262][564,1310]']" ) self.driver.find_element_by_xpath( By.XPATH( "//androidx.appcompat.app.ActionBar.Tab[@content-desc='SCHEDULE']/android.view.ViewGroup" )).click() assert self.driver.find_element_by_accessibility_id( 'Open navigation drawer').is_displayed() assert self.driver.find_element_by_id('titleOnToolbar').is_displayed() assert self.driver.find_element_by_id('actionButton').is_displayed() assert self.driver.find_element_by_id('scroll_to_today').is_displayed() assert self.driver.find_element_by_accessibility_id( 'Display Removed Plan').is_displayed() assert self.driver.find_element_by_id('More options').is_displayed() assert self.driver.find_element_by_id( 'downloadImageView').is_displayed() assert self.driver.find_element_by_id('announceText').is_displayed() assert self.driver.find_element_by_id('displayDate').is_displayed() assert self.driver.find_element_by_id('menuButton').is_displayed() assert self.driver.find_element_by_id( 'displayCustomerName').is_displayed() assert self.driver.find_element_by_id('navigationArrow').is_displayed() assert self.driver.find_element_by_id('listView').is_displayed()
def test_element_to_be_clickable(self): try: WebDriverWait(self.driver, 5).until( EC.element_to_be_clickable( By.XPATH("//button[@title='Subscribe']"))) except TimeoutException: print("Taking more time to load")
class Browse: def __init__(self, driver): self.driver = driver signin = By.CSS_SELECTOR("a.login") loginemail = By.ID("email") loginpassword = By.ID("passwd") loginsubmit = By.ID("SubmitLogin") menu = By.XPATH("//div[@id='block_top_menu']/ul/li/a") searchbar = By.ID("search_query_top") def login(self): return self.driver.find_element(*Browse.signin).click() def logemail(self): return self.driver.find_element(*Browse.loginemail).send_keys("*****@*****.**") def logpassword(self): return self.driver.find_element(*Browse.loginpassword).send_keys("Sindhu124") def logsubmit(self): return self.driver.find_element(*Browse.loginsubmit).click() def search(self): return self.driver.find_element(*Browse.searchbar).send_keys("printed") def searchenter(self): return self.driver.find_element(*Browse.searchbar).send_keys(Keys.ENTER)
def is_no_password_validation_msg_displayed(self): is_msg_displayed = False parent = self._noPasswordValidationMsg().find_element( By.XPATH(str(self._parent_xpath))) classes = parent.get_attribute("class") if "has error" in classes: is_msg_displayed = True return is_msg_displayed
def select_car_type(self, car_type): """ Method to select a car type based on the input :return: """ try: temp_dict = {} price_list = [] lowest_price_vehicle_key = 0 self.driver.find_element_by_xpath( WEB_ELEMENt_VEHICLE_LIST_ARROW).click() self.driver.implicitly_wait(40) WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located( By.XPATH(SELECT_VEHICLE.format(car_type)))) self.driver.find_element_by_xpath(SELECT_VEHICLE).click() WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located( By.XPATH(LIST_FILTERED_SUV_VEHICLES_ONLY))) filtered_vehicles = self.driver.find_elements_by_xpath( LIST_FILTERED_SUV_VEHICLES_ONLY) for vehilcle in filtered_vehicles: i = 1 seat_Numbers = filtered_vehicles.find_element_by_xpath( WEB_ELEMENT_FOUR_DOORS_LIST) DOOR_NUMBERS = filtered_vehicles.find_element_by_xpath( WEB_ELEMENT_FOUR_DOORS_LIST) PRICE = filtered_vehicles.find_element_by_xpath(PRICE_TEXT) temp_dict.update({i: PRICE}) price_list.append(PRICE) i = i + 1 min_price = min(price_list) for key in temp_dict.keys(): if temp_dict[key] == min_price: lowest_price_vehicle_key = key selected_vehicle_name = filtered_vehicles[ lowest_price_vehicle_key].find_element_by_xpath( SELECTED_VEHICLE_NAME).text select_vehicle = filtered_vehicles[ lowest_price_vehicle_key].find_element_by_xpath( SELECT_LOWEST_BUTTON).click() return selected_vehicle_name except Exception as err: logging.error("Issue in selecting the lowest price vehicle") return False
def get_following(self): """Gets the profiles that the user follows.""" followbutton = self.driver.find_element_by_partial_link_text("following") sleep(2) followbutton.click() follows = self.driver.find_elements(By.XPATH("//div[@class='wo9IH']")).get_attribute("title") for i in follows: print(i)
def close_pop_up(self) -> bool: try: element = WebDriverWait(self.driver, 10) \ .until( method=EC.presence_of_element_located(By.XPATH("//div[contains(@class,'close-popup-activity')]"))) element.click() return True except: return False
class Search: def __init__(self, driver): self.driver = driver searchbar = By.ID("search_query_top") searchbar.send_keys("printed") searchbar.send_keys(Keys.ENTER) print( By.XPATH( "//*[@id='center_column']/h1/span[@class='heading-counter']").text)
def agree(self): try: WebDriverWait(self.browser, 3).until( EC.element_to_be_clickable( (By.XPATH('/html/body/div[2]/div/div[2]/div/div/button[1]') ))) except TimeoutException: print("不需要同意") pass
def phagesdb_blast_subroutine(): try: tabs = alignmentBrowser.window_handles alignmentBrowser.switch_to.window(tabs[0]) time.sleep(1) try: try: button_BlastPhagesDB = WebDriverWait(browser, 10).until( ec.element_to_be_clickable( (By.PARTIAL_LINK_TEXT, 'on PhagesDB'))) except Exception as e: alignmentBrowser.refresh() button_BlastPhagesDB = WebDriverWait(browser, 10).until( ec.element_to_be_clickable( (By.PARTIAL_LINK_TEXT, 'on PhagesDB'))) except Exception as e: button_BlastPhagesDB = alignmentBrowser.find_element_by_partial_link_text( 'on PhagesDB') button_BlastPhagesDB_URL = button_BlastPhagesDB.get_attribute( 'href') alignmentBrowser.execute_script(('window.open(\'') + button_BlastPhagesDB_URL + ('\'), \'new window\'')) # clicks ncbi blast button in ncbi page tabs = alignmentBrowser.window_handles alignmentBrowser.switch_to.window(tabs[1]) time.sleep(2.5) alignmentBrowser.find_element_by_name('MainBlastForm').submit() except Exception as e: try: alignmentBrowser.refresh() time.sleep(8) alignmentBrowser.find_element_by_name('MainBlastForm').submit() try: phagesdb_blastbtn = WebDriverWait( alignmentBrowser, 5 ).until( ec.element_to_be_clickable( By.XPATH( '/html/body/div/div[3]/div[2]/div[3]/form/input[3]' ))) phagesdb_blastbtn.click() except Exception as e: '' except Exception as e: alignmentBrowser.minimize_window() print( '\nThe program failed to detect the button (local blast submission button at phages db). Please press it manually.' ) input('Press ENTER to continue.\n') alignmentBrowser.maximize_window()
def is_language(self): # 判断语言是否为英语 # language_English = WebDriverWait(self.drive,50).until(EC.presence_of_element_located( # (By.XPATH('//div[@class="nav-main-list"]/a[1]')))) language_English = self.drive.find_element_by_xpath('//div[@class="nav-main-list"]/a[1]').text if language_English == 'German': pass else: WebDriverWait(self.drive, 50).until(EC.presence_of_element_located( By.XPATH('//*[@class="nav-main-list"]/a[1]'))) self.drive.find_element_by_xpath('//*[@class="nav-main-list"]/a[1]').click()
def select_location(self, location): """ Method to select location from Budget Page :param location: Location to be selected :return: """ try: WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located( By.XPATH(WEBELEMENT_INPUT_LOCATION))) self.driver.find_element_by_xpath( WEBELEMENT_INPUT_LOCATION).send_keys(location) location_element = WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located( By.XPATH(WEBELEMENT_LOCATION_SUGGESTIONS))) location_element.click() location_value = self.driver.find_element_by_xpath( WEBELEMENT_INPUT_LOCATION).text return location_value except Exception: logging.error("issue in selecting the location") return False
class main(): dr = webdriver.Firefox() dr.maximize_window() sleep(5) url = "https://www.imooc.com/user/newlogin" dr.get(url) sleep(3) dr.find_element(By.XPATH('//*[@id="sigin"]/div[1]/h1/span[1]')) sleep(3) dr.find_element(By.NAME("email")).click() sleep(3) dr.find_element(By.NAME("email")).send_keys("*****@*****.**") dr.find_element(By.NAME("password")).send_keys("f12547414") dr.find_element(By.value("登录")).click()
def wait_element_is_clickable(self, element_name, xpath=None, timeout=5): def get_el(self, el_name, seconds): elm = self._wait_for_element(el_name, seconds) return elm.is_enabled() is_clickable = False if element_name: for _ in range(timeout): is_clickable = get_el(self, element_name, timeout) if is_clickable: break time.sleep(1) if not is_clickable: raise AssertionError('Element not clickable') elif xpath: wait = WebDriverWait(self._browser.driver, timeout) wait.until(EC.element_to_be_clickable(By.XPATH(xpath)))
def get_job_ids(driver) -> None: """ Go to job search page and get all the job ids, which can be replaced into the url to get unique links. :param driver: The WebDriver object that is currently in session. :return: None. Example ID: 1805650202 LinkedIn URL: https://www.linkedin.com/jobs/search/?currentJobId=1805650202 """ # 25 job postings on a job search page # <div data-job-id="urn:li:fs_normalized_jobPosting:1805650202"></div> driver.get( 'https://www.linkedin.com/jobs/search/?geoId=90009551&location=Greater%20Toronto%20Area%20Metropolitan%20Area&start=150' ) try: # WebDriverWait(driver, 15).until(EC.visibility_of_element_located( # (By.CSS_SELECTOR, "div.data-control-id"))) # WebDriverWait(driver, 15).until(EC.visibility_of_element_located(By.XPATH("//*[@data-control-id]"))) WebDriverWait(driver, 15).until( EC.visibility_of_element_located( By.XPATH("//div[contains(@data-job-id, " "'urn:li:fs_normalized_jobPosting:1757159406')]"))) # div class: neptune-grid one-column full-height except TimeoutException: print('No element with data-control-id found.') except TypeError: print(type(driver)) # html = BeautifulSoup(driver.page_source, 'html.parser') # lst = html.find_all('div', {'data-control-id': True}) # print(len(lst)) lst = [] try: div = driver.find_elements_by_class_selector("div.data-control-id") lst.append(div) except NoSuchElementException: print('No div element found with data-control-id selector.') except AttributeError: elem = driver.find_elements_by_xpath("//div[contains(@data-job-id)]") print(elem.get_attribute("value")) lst_ids = [] for elem in lst: lst_ids.append(elem.content) print(lst_ids)
def select_element_by_index(self, element, index=0): """select element passing index argument Arguments: element {[webelement]} Keyword Arguments: index {int} (default: {0}) """ try: element = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(By.XPATH(element))) select = Select(element) select.select_by_index(index) self.log.info("Selected element from menu: " + element) except: self.log.info("Could not select element: " + element) print_stack()
def testLogin(self): """ 1.Авторизация в админку личного кабинета 2.Заходим под тестовым лицевым счетом 3.Проверяем что мы в личном кабинете """ driver = self.driver driver.implicitly_wait(10) wait = WebDriverWait(driver, 10) contract = driver.find_element_by_id('adminabonent-contract') submit = driver.find_element_by_class_name('admin-contract-button') contract.send_keys('353829') submit.click() time.sleep(10) menu = wait.until( ec.presence_of_element_located( By.XPATH('/html/body/div[1]/div[1]/a[1]'))) self.assertIn("Личный кабинет", menu)
def getLocator(self, locator): by = None key = locator.split(":") if len(key) == 1: by = By.ID(locator) elif len(key) == 2: key[0] = key[0].lower() key[1] = key[1].strip() if key[0] == "id": by = By.ID(key[1]) if key[0] == "name": by = By.NAME(key[1]) if key[0] == "xpath": by = By.XPATH(key[1]) if key[0] == "linktext": by = By.LINK_TEXT(key[1]) elif key[0] == "particallinktext": by = By.PARTIAL_LINK_TEXT(key[1]) else: print("NO LOCATOR MATCHED") return by
def test_e2e(self): log = self.getLogger() Account = (self.driver) Login = Browse.login() menu_list = [] for m in Browse.menu: menu_list.append(m.text) print(menu_list) for m in Browse.menu: m.click() assert self.driver.title == "Women - My Store" self.driver.find_element_by_css_selector( "a[class*='btn-primary']").click() self.verifyLinkPresence("Women") self.verifyLinkPresence("Dresses") self.verifyLinkPresence("T-Shirts") number = (By.XPATH( "//*[@id='center_column']/h1/span[@class='heading-counter']").text) assert "0" not in number
def req_chrome(): chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--headless') # chrome_options.add_argument('blink-settings=imagesEnabled=false') # chrome_options.add_argument('--disable-gpu') driver = webdriver.Chrome(chrome_options=chrome_options) driver.get("https://weixin.sogou.com/") # driver.find_element_by_xpath("//input[@id='query']").send_keys("̫ƽÑó·¿ÎÝ") driver.find_element_by_xpath("//input[@class='swz']").click() res_txt = driver.page_source res = Selector(text=res_txt) source_url_list = res.xpath("//div[@class='txt-box']/h3/a/@href").extract() print(res) driver.find_element_by_xpath("//div[@class='txt-box']/h3/a").click() print(driver.find_element_by_xpath("//div[@class='txt-box']/h3/a").get(0)) print(driver.find_element(By.XPATH("//div[@class='txt-box']/h3/a"))) print(driver.title) time.sleep(3) driver.close()
from urllib.request import urlopen import xml.etree.ElementTree as ET from selenium import webdriver import time import re from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By caps = DesiredCapabilities.CHROME caps['loggingPrefs'] = {'performance': 'ALL'} driver = webdriver.Chrome(desired_capabilities=caps) driver.get("https://www.youtube.com/watch?v=zppTAkoVKnA") time.sleep(1) try: videoAdUiPreSkipButton = driver.find_element( By.XPATH("//div[@class='videoAdUiPreSkipButton']")) if videoAdUiPreSkipButton.is_displayed() == True: videoAdUiPreSkipButtonFirstDiv = driver.find_element( By.XPATH("//div[@class='videoAdUiPreSkipButton']//div[1]")) videoAdUiPreSkipButtonSECONDDiv = driver time.sleep(2) skipaddbutton = driver.find_element( By.XPATH( "//div[@class='videoAdUiSkipContainer html5-stop-propagation']" )) skipaddbutton.click() except: try: driver.find_element_by_class_name("ytp-subtitles-button").click() except: driver.refresh()
def clean_fields(self, elem): self.driver.find_element(By.XPATH(elem)).clear()
def fluentWaitElementByXpath(location): try: element = WebDriverWait(location.driver, 10).until( EC.presence_of_element_located((By.XPATH(location)))) finally: location.driver.quit()
def select_element_by_text(self, element, text=""): """Seleciona o elemento em um menu do tipo select pelo atributo texto @param locator_type(str): tipo de locator usado na busca @param locator(str): identificador do elemento @param text(str) """ try: element = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(By.XPATH(element))) select = Select(element) select.select_by_visible_text(text) self.log.info("Selected element from menu: " + element) except: self.log.info("Could not select element: " + element) print_stack()
"//input[@name='btnName']") #button = browser.find_element_by_xpath("//input[@name='btnName' and @src='/gfx/btnSearch.jpg']")[0] print(button.get_attribute('value')) button.click() wait = WebDriverWait(browser, 15) wait.until( expected_conditions.presence_of_element_located( (By.CLASS_NAME, 'FLFUNDNAME'))) fundElement = browser.find_element_by_class_name('FLFUNDNAME') print('here') print(fundElement.text) dateElement = fundElement.find_element( By.XPATH("following-sibling::td[@class='FLROW']")) priceElement = dateElement.find_element( By.XPATH("following-sibling::td[@class='FLROW']")) print(dateElement.text) print(priceElement.text) finally: browser.quit() #old_value = browser.find_elements_by_class_name('FLFUNDNAME').text #browser.find_element_by_link_text('popUpWindow2').click() #WebDriverWait(browser, 3).until(expected_conditions.text_to_be_present_in_element((By.ID, 'thing-on-new-page'),'expected new text')) #soup = BeautifulSoup(html_doc, 'html.parser')
class Account: def __init__(self, driver): self.driver = driver signin = By.CSS_SELECTOR("a.login") account_email = By.ID("email_create") create_account = By.ID("SubmitCreate") first_name = By.ID("customer_firstname") last_name = By.ID("customer_lastname") password = By.ID("passwd") address = By.ID("address1") city = By.ID("city") zipcode = By.ID("postcode") states = By.XPATH("//*[@id='id_state']/option[5]") phone_number = By.ID("phone_mobile") address_alias = By.ID("alias") register = By.ID("submitAccount") def signing(self): return self.driver.find_element(*Account.signin).click() def sendemail(self): return self.driver.find_element( *Account.account_email).send_keys("*****@*****.**") def createaccount(self): return self.driver.find_element(*Account.create_account).click() def firstnamesend(self): return self.driver.find_element( *Account.first_name).send_keys("Sindhu") def lastnamesend(self): return self.driver.find_element(*Account.last_name).send_keys("Sh") def passwordsend(self): return self.driver.find_element( *Account.password).send_keys("Sindhu124") def addresssend(self): return self.driver.find_element( *Account.address).send_keys("2421 carlmont") def citysend(self): return self.driver.find_element(*Account.city).send_keys("Belmont") def statesend(self): return self.driver.find_element(*Account.states).click() def zipcodesend(self): return self.driver.find_element(*Account.zipcode).send_keys("94002") def phonesend(self): return self.driver.find_element( *Account.phone_number).send_keys("6504036567") def addressaliassend(self): return self.driver.find_element( *Account.address_alias).send_keys("Bangalore India") def registered(self): return self.driver.find_element(*Account.register).click()