def find_by_swip(driver: WebDriver, by, locator) -> WebElement: driver.implicitly_wait(1) elements = driver.find_elements(by, locator) while len(elements) == 0: driver.swipe(0, 600, 0, 400) elements = driver.find_elements(by, locator) driver.implicitly_wait(5) return elements[0]
def test_js_release_cdn(self, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: Tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "2.0.0") monkeypatch.setattr(resources, "__version__", "2.0.0") r = deepcopy(CDN) # Skip bokeh-mathjax for older versions r.js_components.remove("bokeh-mathjax") js, tag = bes.autoload_static(test_plot, r, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(By.CSS_SELECTOR, 'head script') for x in scripts: print(x.get_attribute("src")) assert len(scripts) == 4 for script in scripts: assert script.get_attribute("crossorigin") == None assert script.get_attribute("integrity") == ""
def __call__(self, driver: WebDriver): elements = driver.find_elements(self.by, self.locator) if len(elements) > 0: a = elements[0].get_attribute(self.attribute) #print(a) return a else: return False
def download_all_pdfs(driver: WebDriver) -> List[Dict[str, bytes]]: import requests anchors = driver.find_elements(by=PDF_LINKS.by, value=PDF_LINKS.value) hrefs = [anchor.get_property("href") for anchor in anchors] responses = [requests.get(href) for href in hrefs] assert all(response.status_code == 200 for response in responses) logging.debug(f"Successfully downloaded all {len(hrefs)} PDFs") pdfs = [{"href": response.url, "pdf": response.content} for response in responses] return pdfs
def is_element_present(driver: WebDriver, selector: Selector) -> bool: """Check if sought element is present""" try: elements = driver.find_elements(by=selector.by, value=selector.value) if elements: logging.debug(f"Found following elements: {elements}") found = True else: found = False except NoSuchElementException: found = False return found
def test_js_dev_cdn(self, version: str, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: Tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "1.4.0rc1") monkeypatch.setattr(resources, "__version__", "1.4.0rc1") js, tag = bes.autoload_static(test_plot, CDN, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(By.CSS_SELECTOR, 'head script') assert len(scripts) == 5 for script in scripts: assert script.get_attribute("crossorigin") == None assert script.get_attribute("integrity") == ""
def wait_for_next(x: WebDriver): try: x.find_elements(*locator).click() return x.find_element(By.ID, 'username') except: return False
def find_elements(driver: WebDriver, selector: Selector) -> List[WebElement]: """Find element by CSS selector or it's ID.""" with selenium_action(driver, f"Couldn't find elements using '{selector.value}'"): elements = driver.find_elements(by=selector.by, value=selector.value) return elements
def transaction_parser( cls, driver: WebDriver, account: AbstractAccount ) -> Iterator[Optional['SberbankTransaction']]: """Parse Sberbank transaction.""" transactions_table = driver.find_element(By.ID, 'simpleTable0') with suppress(NoSuchElementException): driver.find_element(By.XPATH, "//div[contains(@class, 'emptyText')]") logger.info( f'Not found new transactions for account {account.name}') return if driver.find_element(By.ID, 'pagination').is_displayed(): # Many transactions. Increase the number of elements per page driver.find_elements( By.XPATH, "//span[contains(@class, 'paginationSize')]")[-1].click() transactions_table = driver.find_element(By.ID, 'simpleTable0') while True: curr_day_transactions = [] prev_transaction_data = cls._transaction_time_parse('Сегодня') for transaction_el in transactions_table.find_elements( By.XPATH, ".//tr[contains(@class, 'ListLine')]"): raw_info = [ i.text for i in transaction_el.find_elements(By.XPATH, "./td") ] curr_transaction_date = cls._transaction_time_parse( raw_info[3]) raw_cost, raw_currency = raw_info[4].rsplit(' ', 1) raw_transaction = { 'account_name': account.name, 'tr_time': curr_transaction_date, 'cost': replace_formatter(raw_cost, delete_symbols=' ', custom={',': '.'}), 'currency': currency_converter(raw_currency), 'description': raw_info[0].rsplit('\n', 1)[0], } if prev_transaction_data == curr_transaction_date: logger.debug( f'add to {curr_transaction_date} transaction {raw_transaction}' ) curr_day_transactions.append(raw_transaction) else: logger.debug( f'return transactions {curr_day_transactions} for {prev_transaction_data}' ) yield from cls._add_custom_unique_tr_id( curr_day_transactions) curr_day_transactions.clear() prev_transaction_data = curr_transaction_date logger.debug( f'add to {curr_transaction_date} transaction {raw_transaction}' ) curr_day_transactions.append(raw_transaction) paginator = transactions_table.find_element(By.ID, 'pagination') if paginator.is_displayed(): # go to next page paginator_next = paginator.find_elements( By.XPATH, ".//table[contains(@class, 'tblPagin')]//td")[2] with suppress(NoSuchElementException): # if only one page with transaction results - be error here. Ignoring... button = paginator_next.find_element( By.XPATH, ".//div[contains(@class, 'activePaginRightArrow')]") if button.get_attribute('class').startswith('inactive'): # if last page logger.debug( f'return transactions {curr_day_transactions} for {prev_transaction_data}' ) yield from cls._add_custom_unique_tr_id( curr_day_transactions) break button.click() def wait_new_table(): # waiting new page with transactions WebDriverWait(driver, TIMEOUT).until( expected_conditions.presence_of_element_located( (By.ID, 'simpleTable0'))) retry = Retry( function=wait_new_table, error=SeleniumTimeoutException, err_msg= (f'Error. WebDriver not found page with new transactions for timeout {TIMEOUT}.' ' Please, check your network connection'), max_attempts=3) retry() else: logger.debug( f'return transactions {curr_day_transactions} for {prev_transaction_data}' ) yield from cls._add_custom_unique_tr_id(curr_day_transactions) break
def __call__(self, driver: WebDriver): elements = driver.find_elements( By.XPATH, f'//*[contains(text(), "{self.text}")]', ) return elements or False
def run(driver: WebDriver): nonlocal no if not no: elem = driver.find_element(By.XPATH, "//a[text()='投票']") if not elem: elem = driver.find_element(By.XPATH, "//a[text()='今日已投票']") if elem: driver.delete_all_cookies() driver.refresh() return None elem.click() elem_container = driver.find_element_by_class_name( "modal__container") if elem_container.is_displayed(): no += 1 return elem_container elif no == 1: elem_vote_options = driver.find_elements( By.XPATH, "//div/div/label[@class='label']") if not elem_vote_options: return None for elem in elem_vote_options: if not elem.is_displayed(): break elem.click() for_input = driver.find_element_by_id( elem.get_attribute("for")) if not for_input.is_selected(): break else: no += 1 return elem_vote_options if no == 2: driver.add_cookie({ "name": "uuid", "value": generate_uuid(), "domain": ".businessweekly.com.tw", "size": 40, }) elem = None try: elem = driver.find_element(By.XPATH, r"//a[text()='確認送出']") if elem and elem.is_enabled(): elem.click() except Exception as e: if driver.find_element_by_id("gdrp-el"): driver.execute_script( """document.getElementById("gdrp-el").remove();""") finally: elem_container = driver.find_element_by_class_name( "modal__container") if elem_container and elem_container.find_element( By.XPATH, "//img[@alt='投票完成']"): no += 1 return True if "投票完成" in driver.page_source: no += 1 return True return None
def find_elements_func(driver: WebDriver): elements["found"] = driver.find_elements(*locator) elements["result"] = list( filter(desired_state.element_state_condition, elements["found"])) return any(elements["result"])
def find_elements(driver: WebDriver, selector: Selector) -> List[WebElement]: """Find elements by specific selector.""" with selenium_action(driver, f"Can't find elements with {selector.value}"): elements = driver.find_elements(by=selector.by, value=selector.value) return elements
''' Created on Nov 9, 2019 @author: DELL ''' from selenium import webdriver from selenium.webdriver.common.by import By from collections import Collection from selenium.webdriver.remote.webdriver import WebDriver # driver = webdriver.Chrome(executable_path='C:/Users/DELL/git/Selenium_NSE_Algo/Additonal_Utility/chromedriver_242') driver = WebDriver(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=True, options=None) driver.get("https://www.moneycontrol.com/") welist = driver.find_elements(By.XPATH, ("//div[@id]/div/ul/li")) for i, ele in enumerate(welist): obj_driv = welist[i] print(ele.location)