def download_lesson(driver: WebDriver, lesson: WebElement, module_path: pathlib.Path) -> None: lesson_url = lesson.get_attribute('href') course_page = driver.current_window_handle driver.execute_script('window.open()') driver.switch_to.window(driver.window_handles[1]) driver.get(lesson_url) youtube_url = get_youtube_url(driver) if youtube_url is not None: # BUG: the output option is not working; fix it; output_path = module_path / '%(title)s.%(ext)s' ydl_opts = { 'output': str(output_path), 'retries': 10, } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([youtube_url]) except youtube_dl.utils.DownloadError as e: print(e) driver.close() driver.switch_to.window(course_page)
class SeleniumTest(TestCase): """Testing google.com""" def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(5) self.browser.get('http://google.com') def tearDown(self): self.browser.close() def search(self, search_string): q = self.browser.find_element_by_name('q') q.send_keys(search_string) q.submit() results = self.browser.find_element_by_id('search') return results.find_elements_by_tag_name('a') def test_python(self): for link in self.search('python'): if 'https://www.python.org/' in (link.get_attribute('href') or ''): break else: self.fail('python.com is not on google results page') def test_python_in_title(self): self.search('python django') assert 'python' in self.browser.title
def installAddon_cleanTabs_getLoginWindow(self, driver: WebDriver) -> None: """ 1) Install UblockOrigin 2) If any "welcome" windows open, close them 3) Click on login button """ driver.install_addon( f"{self.cfg['EXTENSIONS']['FOX_EXT_BASE_PATH']}/{self.cfg['EXTENSIONS']['UBO']}" ) driver.get(self.cfg["LOGIN"]["LOGIN_FROM"]) WebDriverWait(self.driver, 7).until( EC.presence_of_all_elements_located((By.TAG_NAME, "main"))) # wait for the page to load # Points to ww login-page MAIN_HANDLE: str = driver.current_window_handle for window_handle in driver.window_handles: if window_handle != MAIN_HANDLE: driver.switch_to.window(window_handle) # after closing all irrelevant tabs driver will focus back to the main one driver.close() # Puts focus back on ww login-page driver.switch_to.window(MAIN_HANDLE) # Use this stuff to setup the login window (You don't want any junk in some new tab) sleep(2) # click the first button on the page, it will make login button visible driver.execute_script( self.clickFirstElementFromElementList("button") + self.clickElementWithInnerTextS("button", "log in"))
def close_current_tab_and_switch_to_window( browser: webdriver.WebDriver, window_to_switch_to: webdriver.WebDriver = None): logging.info("Closing current tab") wait() browser.close() logging.info("Switching to previously opened tab") if window_to_switch_to is None: browser.switch_to.window( browser.window_handles[get_last_opened_tab_id(browser)]) else: browser.switch_to.window(window_to_switch_to)
class TestFirefox(LiveServerTestCase): """To test a user story using Firefox""" def setUp(self): self.selenium = WebDriver() self.selenium.implicitly_wait(10) self.selenium.maximize_window() temp_user_creation() db_init() def tearDown(self): self.selenium.close() def test_login(self): """Test when the user wants to log in""" self.selenium.get('%s%s' % (self.live_server_url, '/authentication/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys('*****@*****.**') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('test2020') submit = self.selenium.find_element_by_id("submit-button") submit.send_keys(Keys.RETURN) def test_search_product_details(self): """To test when the user wants to search a prod and its details""" self.selenium.get('%s%s' % (self.live_server_url, '/')) query_input = self.selenium.find_element_by_id("query") query_input.send_keys('nutella') search = self.selenium.find_element_by_id("search-btn") search.send_keys(Keys.RETURN) product = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='details-link']"))) product.click() def test_save_product(self): """To test when the user wants to save a product""" self.test_login() query_input = self.selenium.find_element_by_id("query") query_input.send_keys('nutella') search = self.selenium.find_element_by_id("search-btn") search.send_keys(Keys.RETURN) product = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.ID, "product-title"))) product.click() substitute = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='save-btn']"))) substitute.click() def test_logout(self): self.test_login() logout = WebDriverWait(self.selenium, 30).until( EC.element_to_be_clickable((By.XPATH, "//*[@id='logout']"))) logout.click()
def go_to_page(browser: webdriver.WebDriver, url, test_element_xpath): if browser.current_url != url: browser.set_page_load_timeout(3) try: browser.get(url) except TimeoutException: try: browser.set_page_load_timeout(10) browser.get(url) except TimeoutException: logging.error("The URL " + url + " is unreachable") browser.close() wait_for_page(browser, url, test_element_xpath)
def run(*, driver: WebDriver, url: str, opt: int): driver.get(url) try: main_node = driver.find_element_by_xpath("/html/body/form/div[1]") els: list = main_node.find_elements_by_tag_name("input") el = els[int(opt) - 1] driver.execute_script("arguments[0].click();", el) # delay time.sleep(3) logger.info("ok") except: # noqa logger.info("ko") finally: driver.close()
def decline_offer(offer_reference): driver = WebDriver() # Login selenium_login(webdriver=driver) # Decline offer driver.get('https://www.odesk.com/applications/%s' % offer_reference) driver.find_element_by_id("declineButton").click() driver.find_element_by_css_selector("option[value=\"146\"]").click() driver.find_element_by_id("otherReason").clear() driver.find_element_by_id("otherReason").send_keys("Test") driver.find_element_by_xpath("(//a[contains(text(),'Decline')])[2]").click() driver.close()
def test(self): # Setup driver = WebDriver() db = {'plane': [], 'crew': [], 'flight': []} for i in range(5): a = Airplane(registerNumber=i + 10000, places=20) a.save() db['plane'].append(a) b = AirplaneCrew(captainsName="X{}".format(i + 10000), captainsSurname="Z{}".format(i + 1)) b.save() db['crew'].append(b) db['flight'].append(Flight.objects.create(startAirport="A", endAirport="B", airplane=a, crew=b, startTime=self.date, endTime=self.date + timedelta(hours=4))) User.objects.create_user(username='******', password='******') # Log in driver.get("{}/".format(self.live_server_url)) driver.find_element_by_id("login_dropdown").click() driver.find_element_by_id("login_username").send_keys("d") driver.find_element_by_id("login_password").send_keys("d") driver.find_element_by_id("login_button").click() # Buying ticket driver.get("{}/flight/1".format(self.live_server_url)) driver.find_element_by_id("name").send_keys("A") driver.find_element_by_id("surname").send_keys("B") driver.find_element_by_id("buy_ticket_button").click() # Check if bought correctly counter = 0 expected_results = ["A", "B", "1"] for td in driver.find_elements_by_tag_name("td"): self.assertEqual(td.text, expected_results[counter]) counter += 1 # Assigning incorrect crews driver.get("{}/static/crews.html".format(self.live_server_url)) driver.find_element_by_id("change_crew_assignment").click() Select(driver.find_element_by_id("flight_select")).select_by_index(1) driver.find_element_by_id("change_crew_assignment").click() try: WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "error_alert")) ) finally: error_message = "Error - couldn't assign crew! You have to be logged in!" self.assertEqual(driver.find_element_by_class_name("alert").text, error_message) driver.close()
def send_offer(cipher, job_reference, client, buyer_reference, worker_reference): driver = WebDriver() driver.implicitly_wait(time_to_wait=10) # Login selenium_login(webdriver=driver) # Worker's page driver.get('https:/www.odesk.com/users/%s' % cipher) driver.find_element_by_link_text("Contact").click() # Make an offer link driver.find_element_by_id("jsMakeOfferLink").click() el = driver.find_element_by_css_selector("#jsTeamSelector > select") el.find_element_by_css_selector("option[value=\"%s\"]" % buyer_reference).\ click() driver.find_element_by_id("jsMakeOfferProceed").click() # Sign in to make an offer driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(settings.ODESK_TEST_ACC_PASS) try: driver.find_element_by_id("answer").clear() driver.find_element_by_id("answer").send_keys(settings.ODESK_TEST_ACC_ANSWER) except selenium.exceptions.NoSuchElementException: pass driver.find_element_by_id("submitButton").click() # Make an offer form driver.find_element_by_id("useExistingJob-yes").click() el = driver.find_element_by_id("jobPosting") el.find_element_by_css_selector("option[value=\"%s\"]" % job_reference).\ click() driver.find_element_by_id("employerRate").clear() driver.find_element_by_id("employerRate").send_keys("0.01") driver.find_element_by_id("setLimit-yes").click() driver.find_element_by_id("limit").clear() driver.find_element_by_id("limit").send_keys("0") driver.find_element_by_id("submitButton").click() # Agreement driver.find_element_by_id("agreement").click() driver.find_element_by_id("submitButton").click() driver.close()
def get_watcher_window(driver: WebDriver, wait: WebDriverWait) -> Union[bool, int, str]: """ driverを取得した直後に呼ぶ Watcherタブ以外を消してWatcherタブを開く """ watcher_window = False logger.debug("Try to access extension page") try: wait.until( expected_conditions.visibility_of_all_elements_located( (By.ID, "button"))) wait.until( expected_conditions.presence_of_element_located( (By.ID, "DoneAttachJS"))) except TimeoutException as err: print(f"failed to access extension page by timeout: {err}") return False except Exception as err: print(f'failed to access extension page: {err}') return False try: windows: list[Union[int, str]] = driver.window_handles for window in windows: driver.switch_to.window(window) title = driver.title if title == "Watcher": watcher_window = window else: # 不要なページを消す driver.close() except Exception as err: # 最悪、エラーが起きてもwatcher_windowがわかればよい pass try: driver.switch_to.window(watcher_window) except Exception as err: logger.exception(f"Faild to switch extension page: {err}") return False else: return watcher_window
def get_balance(browser: WebDriver, url: str, card_number: str) -> str: input_field_id = 'ean' balance_field_class = 'history_header_amount' browser.get(url) time.sleep(0.5) # num_form = WebDriverWait(browser, 5).until( # expected_conditions.presence_of_element_located( # (By.ID, input_field_id) # ) # ) num_form = browser.find_element_by_name(input_field_id) num_form.send_keys(card_number) num_form.submit() try: balance_field = WebDriverWait(browser, 5).until( expected_conditions.presence_of_element_located( (By.CLASS_NAME, balance_field_class))) balance = balance_field.text except TimeoutException: error = browser.find_element_by_class_name( 'form-messages_message__error') errors = [ 'Проверьте корректность введенных данных', 'Введите корректный номер штрих-кода карты', ] if error.text in errors: balance = 'Карта не найдена' else: balance = error.text finally: browser.close() return balance
def test_no_disclaimer_when_search_engine(self): profile = webdriver.FirefoxProfile() profile.set_preference( "general.useragent.override", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" ) browser = WebDriver(profile) browser.implicitly_wait(10) browser.set_window_size(width=1200, height=1200) old_browser = self.browser self.set_browser(browser) try: self.visit_home() self.find('#disclaimer').get_attribute('class').should.contain('fade') finally: browser.close() self.set_browser(old_browser) self.set_default_window_size() self.try_to_revive_browser()
def test_no_disclaimer_when_search_engine(self): profile = webdriver.FirefoxProfile() profile.set_preference( "general.useragent.override", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" ) browser = WebDriver(profile) browser.implicitly_wait(10) browser.set_window_size(width=1200, height=1200) old_browser = self.browser self.set_browser(browser) try: self.visit_home() self.find('#disclaimer').get_attribute('class').should.contain( 'fade') finally: browser.close() self.set_browser(old_browser) self.set_default_window_size() self.try_to_revive_browser()
def rm_other_than_watcher(driver: WebDriver, wait: WebDriverWait, watcher_window: Union[str, int]) -> Union[int, str]: """ Watcherタブ以外を消してWatcherタブを開く """ logger.debug("rm_other_than_watcher...") try: windows = driver.window_handles except Exception as err: logger.exception(f"{err}") return watcher_window windows = cast(List[Union[int, str]], windows) for window in windows: driver.switch_to.window(window) title = driver.title if title == "Watcher": watcher_window = window else: try: # 不要なページを消す logger.info("close some window") driver.close() except Exception as err: logger.exception(f"failed to close window {err}") pass try: driver.switch_to.window(watcher_window) except Exception as err: logger.exception(f"Faild to switch extension page: {err}") pass logger.debug("rm_other_than_watcher... FIN") return watcher_window
from selenium.webdriver.firefox.webdriver import WebDriver wd = WebDriver() wd.implicitly_wait(60) wd.get("https://encrypted.google.com/") wd.find_element_by_id("gbqfq").click() wd.find_element_by_id("gbqfq").clear() wd.find_element_by_id("gbqfq").send_keys("santiago suarez ordoñez") wd.find_element_by_xpath("//ol[@id='rso']//em[.='Santiago Suarez Ordoñez']").click() wd.close()
def check_availability_and_reserve(driver: WebDriver, url: str, reserved_count=[-1]): desired_date = date.today().strftime("%m-%Y") does_discord_want_stop = check_if_need_to_stop_from_discord() if does_discord_want_stop: print("Stopping from discord command after running") driver.close() driver.quit() return check_if_need_to_short_circuit() global desired_date_global if desired_date_global != "": date_split = desired_date.split("-") desired_date = f"{date_split[0]}/{desired_date_global}/{date_split[1]}" else: desired_date = date.today().strftime("%m/%d/%Y") print(desired_date) if reserved_count[0] == 5: global wait_global wait_global = True return runner() try: while True: driver.get(url) # Only log in the first attempt if reserved_count[0] == -1: wait_for_login_screen_or_refresh_till_success( driver, "SingleDatePickerInput_calendarIcon", runner, None) log_in(driver) reserved_count[0] += 1 print("\nWaiting for page to load...") WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.CLASS_NAME, "SingleDatePickerInput_calendarIcon"))) print("Page has loaded!") increase_quantity_to_two(driver) navigate_to_date(driver, desired_date, "DateInput_input_1", False) check_if_shuttle_times_are_available(driver, url, reserved_count) WebDriverWait(driver, 5).until( EC.presence_of_element_located( (By.CLASS_NAME, "ti-radio-pill-available"))) intended_times: list[ WebElement] = driver.find_elements_by_class_name( "ti-radio-pill-time") add_shuttle_to_cart(driver, intended_times, desired_date, reserved_count) print("Restarting checking process.\n") smart_sleep() return check_availability_and_reserve(driver, url, reserved_count) print("Page is refreshed.") except Exception as e: print(e) finally: # print('Attempting to restart script') # runner(sys.argv[1]) pass
from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.webdriver import WebDriver options = Options() options.headless = True driver = WebDriver(firefox_options=options) driver.get('https://ke.qq.com') driver.save_screenshot('ke.png') driver.close() driver.quit()