text
stringlengths
81
112k
Show the first element on the page that matches the selector. def show_element(self, selector, by=By.CSS_SELECTOR): """ Show the first element on the page that matches the selector. """ selector, by = self.__recalculate_selector(selector, by) selector = self.convert_to_css_selector(selector, by...
Show all elements on the page that match the selector. def show_elements(self, selector, by=By.CSS_SELECTOR): """ Show all elements on the page that match the selector. """ selector, by = self.__recalculate_selector(selector, by) selector = self.convert_to_css_selector(selector, by=by) ...
Remove the first element on the page that matches the selector. def remove_element(self, selector, by=By.CSS_SELECTOR): """ Remove the first element on the page that matches the selector. """ selector, by = self.__recalculate_selector(selector, by) selector = self.convert_to_css_selector(select...
Remove all elements on the page that match the selector. def remove_elements(self, selector, by=By.CSS_SELECTOR): """ Remove all elements on the page that match the selector. """ selector, by = self.__recalculate_selector(selector, by) selector = self.convert_to_css_selector(selector, by=by) ...
BeautifulSoup is a toolkit for dissecting an HTML document and extracting what you need. It's great for screen-scraping! def get_beautiful_soup(self, source=None): """ BeautifulSoup is a toolkit for dissecting an HTML document and extracting what you need. It's great for screen-scraping...
Get all unique links in the html of the page source. Page links include those obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". def get_unique_links(self): """ Get all unique links in the html of the page source. Page links include those obtained...
Get the status code of a link. If the timeout is exceeded, will return a 404. For a list of available status codes, see: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes def get_link_status_code(self, link, allow_redirects=False, timeout=5): """ Get the status code of...
Assert no 404 errors from page links obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". def assert_no_404_errors(self, multithreaded=True): """ Assert no 404 errors from page links obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src"....
Finds all unique links in the html of the page source and then prints out those links with their status codes. Format: ["link" -> "status_code"] (per line) Page links include those obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". def pri...
When executing a script that contains a jQuery command, it's important that the jQuery library has been loaded first. This method will load jQuery if it wasn't already loaded. def safe_execute_script(self, script): """ When executing a script that contains a jQuery command, ...
Creates a folder of the given name if it doesn't already exist. def create_folder(self, folder): """ Creates a folder of the given name if it doesn't already exist. """ if folder.endswith("/"): folder = folder[:-1] if len(folder) < 1: raise Exception("Minimum folder name...
Take a screenshot of an element and save it as an image file. If no folder is specified, will save it to the current folder. def save_element_as_image_file(self, selector, file_name, folder=None): """ Take a screenshot of an element and save it as an image file. If no folder is specifie...
Downloads the file from the url to the destination folder. If no destination folder is specified, the default one is used. (The default downloads folder = "./downloaded_files") def download_file(self, file_url, destination_folder=None): """ Downloads the file from the url to the destina...
Similar to self.download_file(), except that you get to rename the file being downloaded to whatever you want. def save_file_as(self, file_url, new_file_name, destination_folder=None): """ Similar to self.download_file(), except that you get to rename the file being downloaded to whatev...
Saves the data specified to a file of the name specified. If no destination folder is specified, the default one is used. (The default downloads folder = "./downloaded_files") def save_data_as(self, data, file_name, destination_folder=None): """ Saves the data specified to a file of the...
Asserts that there are no JavaScript "SEVERE"-level page errors. Works ONLY for Chrome (non-headless) and Chrome-based browsers. Does NOT work on Firefox, Edge, IE, and some other browsers: * See https://github.com/SeleniumHQ/selenium/issues/1161 Based on the followin...
Returns a time-based one-time password based on the Google Authenticator password algorithm. Works with Authy. If "totp_key" is not specified, defaults to using the one provided in seleniumbase/config/settings.py Google Auth passwords expire and change at 30-second interv...
This method converts a selector to a CSS_SELECTOR. jQuery commands require a CSS_SELECTOR for finding elements. This method should only be used for jQuery/JavaScript actions. Pure JavaScript doesn't support using a:contains("LINK_TEXT"). def convert_to_css_selector(self, selector, b...
This method uses JavaScript to update a text field. def set_value(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ This method uses JavaScript to update a text field. """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: t...
Same as self.set_value() def js_update_text(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ Same as self.set_value() """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) ...
This method uses jQuery to update a text field. If the new_value string ends with the newline character, WebDriver will finish the call, which simulates pressing {Enter/Return} after the text is entered. def jquery_update_text_value(self, selector, new_value, by=By.CSS_SELECTOR, ...
The shorter version of self.jquery_update_text_value() (The longer version remains for backwards compatibility.) def jquery_update_text(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ The shorter version of self.jquery_update_text_value...
Selects an HTML <select> option by specification. Option specifications are by "text", "index", or "value". Defaults to "text" if option_by is unspecified or unknown. def __select_option(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, option_by="text", ...
Selects an HTML <select> option by option text. @Params dropdown_selector - the <select> selector option - the text of the option def select_option_by_text(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeo...
This method opens the start_page, creates a referral link there, and clicks on that link, which goes to the destination_page. (This generates real traffic for testing analytics software.) def generate_referral(self, start_page, destination_page): """ This method opens the start_page, cr...
Similar to generate_referral(), but can do multiple loops. def generate_traffic(self, start_page, destination_page, loops=1): """ Similar to generate_referral(), but can do multiple loops. """ for loop in range(loops): self.generate_referral(start_page, destination_page) time.sl...
Use this method to chain the action of creating button links on one website page that will take you to the next page. (When you want to create a referral to a website for traffic generation without increasing the bounce rate, you'll want to visit at least one additional p...
Similar to generate_referral_chain(), but for multiple loops. def generate_traffic_chain(self, pages, loops=1): """ Similar to generate_referral_chain(), but for multiple loops. """ for loop in range(loops): self.generate_referral_chain(pages) time.sleep(0.05)
Similar to wait_for_element_present(), but returns nothing. Waits for an element to appear in the HTML of a page. The element does not need be visible (it may be hidden). Returns True if successful. Default timeout = SMALL_TIMEOUT. def assert_element_present(self, selector, by=By.CS...
Waits for an element to appear in the HTML of a page. The element must be visible (it cannot be hidden). def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ Waits for an element to appear in the HTML of a page. ...
The shorter version of wait_for_element_visible() def wait_for_element(self, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ The shorter version of wait_for_element_visible() """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: ti...
Same as self.assert_element() As above, will raise an exception if nothing can be found. def assert_element_visible(self, selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): """ Same as self.assert_element() As above, will raise an exception if ...
The shorter version of wait_for_text_visible() def wait_for_text(self, text, selector="html", by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ The shorter version of wait_for_text_visible() """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: t...
Same as assert_text() def assert_text_visible(self, text, selector="html", by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): """ Same as assert_text() """ if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeou...
Similar to assert_text(), but the text must be exact, rather than exist as a subset of the full text. (Extra whitespace at the beginning or the end doesn't count.) Raises an exception if the element or the text is not found. Returns True if successful. Default timeout = S...
The shorter version of wait_for_link_text_visible() def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT): """ The shorter version of wait_for_link_text_visible() """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout...
Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT): """ Similar to wait_for_link_text_...
Same as wait_for_partial_link_text() - returns the element def find_partial_link_text(self, partial_link_text, timeout=settings.LARGE_TIMEOUT): """ Same as wait_for_partial_link_text() - returns the element """ if self.timeout_multiplier and timeout == settings.LARGE_TIME...
Similar to wait_for_partial_link_text(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. def assert_partial_link_text(self, partial_link_text, timeout=settings.SMALL_TIM...
Waits for an element to no longer appear in the HTML of a page. A hidden element still counts as appearing in the page HTML. If an element with "hidden" status is acceptable, use wait_for_element_not_visible() instead. def wait_for_element_absent(self, selector, by=By.CSS_SELECTOR, ...
Similar to wait_for_element_absent() - returns nothing. As above, will raise an exception if the element stays present. Returns True if successful. Default timeout = SMALL_TIMEOUT. def assert_element_absent(self, selector, by=By.CSS_SELECTOR, timeout=settings.SMALL...
Similar to wait_for_element_not_visible() - returns nothing. As above, will raise an exception if the element stays visible. Returns True if successful. Default timeout = SMALL_TIMEOUT. def assert_element_not_visible(self, selector, by=By.CSS_SELECTOR, timeout...
Sets driver control to the specified browser frame. def switch_to_frame(self, frame, timeout=settings.SMALL_TIMEOUT): """ Sets driver control to the specified browser frame. """ if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) ...
Opens a new browser tab/window and switches to it by default. def open_new_window(self, switch_to=True): """ Opens a new browser tab/window and switches to it by default. """ self.driver.execute_script("window.open('');") time.sleep(0.01) if switch_to: self.switch_to_window(...
*** Automated Visual Testing with SeleniumBase *** The first time a test calls self.check_window() for a unique "name" parameter provided, it will set a visual baseline, meaning that it creates a folder, saves the URL to a file, saves the current window screenshot to a...
The screenshot will be in PNG format. def save_screenshot(self, name, folder=None): """ The screenshot will be in PNG format. """ return page_actions.save_screenshot(self.driver, name, folder)
This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method uses the same as the default driver. @Params ...
When using --timeout_multiplier=#.# def __get_new_timeout(self, timeout): """ When using --timeout_multiplier=#.# """ try: timeout_multiplier = float(self.timeout_multiplier) if timeout_multiplier <= 0.5: timeout_multiplier = 0.5 timeout = int(math.ce...
This method extracts the message from an exception if there was an exception that occurred during the test, assuming that the exception was in a try/except block and not thrown. def __get_exception_message(self): """ This method extracts the message from an exception if there ...
If Chromedriver is out-of-date, make it clear! Given the high popularity of the following StackOverflow article: https://stackoverflow.com/questions/49162667/unknown-error- call-function-result-missing-value-for-selenium-send-keys-even ... the original error message was not helpf...
Add a delayed_assert failure into a list for future processing. def __add_delayed_assert_failure(self): """ Add a delayed_assert failure into a list for future processing. """ current_url = self.driver.current_url message = self.__get_exception_message() self.__delayed_assert_failures.a...
A non-terminating assertion for an element on a page. Failures will be saved until the process_delayed_asserts() method is called from inside a test, likely at the end of it. def delayed_assert_element(self, selector, by=By.CSS_SELECTOR, timeout=settings.MINI_TIME...
A non-terminating assertion for text from an element on a page. Failures will be saved until the process_delayed_asserts() method is called from inside a test, likely at the end of it. def delayed_assert_text(self, text, selector="html", by=By.CSS_SELECTOR, timeout=s...
To be used with any test that uses delayed_asserts, which are non-terminating verifications that only raise exceptions after this method is called. This is useful for pages with multiple elements to be checked when you want to find as many bugs as possible in a single tes...
Clicks an element using pure JS. Does not use jQuery. def __js_click(self, selector, by=By.CSS_SELECTOR): """ Clicks an element using pure JS. Does not use jQuery. """ selector, by = self.__recalculate_selector(selector, by) css_selector = self.convert_to_css_selector(selector, by=by) c...
When a link may be hidden under a dropdown menu, use this. def __click_dropdown_link_text(self, link_text, link_css): """ When a link may be hidden under a dropdown menu, use this. """ soup = self.get_beautiful_soup() drop_down_list = soup.select('[class*=dropdown]') for item in soup.se...
Be careful if a subclass of BaseCase overrides setUp() You'll need to add the following line to the subclass setUp() method: super(SubClassOfBaseCase, self).setUp() def setUp(self, masterqa_mode=False): """ Be careful if a subclass of BaseCase overrides setUp() You'll need to ad...
self.__last_page_screenshot is only for pytest html report logs self.__last_page_screenshot_png is for all screenshot log files def __set_last_page_screenshot(self): """ self.__last_page_screenshot is only for pytest html report logs self.__last_page_screenshot_png is for all screenshot...
Be careful if a subclass of BaseCase overrides setUp() You'll need to add the following line to the subclass's tearDown(): super(SubClassOfBaseCase, self).tearDown() def tearDown(self): """ Be careful if a subclass of BaseCase overrides setUp() You'll need to add the following l...
Upload a given file from the file_path to the bucket with the new name/path file_name. def upload_file(self, file_name, file_path): """ Upload a given file from the file_path to the bucket with the new name/path file_name. """ upload_key = Key(bucket=self.bucket, name=file_name)...
Create an index.html file with links to all the log files that were just uploaded. def upload_index_file(self, test_address, timestamp): """ Create an index.html file with links to all the log files that were just uploaded. """ global already_uploaded_files already_uploa...
Allows you to use Bootstrap Tours with SeleniumBase http://bootstraptour.com/ def activate_bootstrap(driver): """ Allows you to use Bootstrap Tours with SeleniumBase http://bootstraptour.com/ """ bootstrap_tour_css = constants.BootstrapTour.MIN_CSS bootstrap_tour_js = constants.Bootstra...
Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ def activate_hopscotch(driver): """ Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ """ hopscotch_css = constants.Hopscotch.MIN_CSS hopscotch_js = constants....
Allows you to use IntroJS Tours with SeleniumBase https://introjs.com/ def activate_introjs(driver): """ Allows you to use IntroJS Tours with SeleniumBase https://introjs.com/ """ intro_css = constants.IntroJS.MIN_CSS intro_js = constants.IntroJS.MIN_JS verify_script = ("""// Verif...
Allows you to use Shepherd Tours with SeleniumBase http://github.hubspot.com/shepherd/docs/welcome/ def activate_shepherd(driver): """ Allows you to use Shepherd Tours with SeleniumBase http://github.hubspot.com/shepherd/docs/welcome/ """ shepherd_js = constants.Shepherd.MIN_JS sh_theme...
Plays a Shepherd tour on the current website. def play_shepherd_tour(driver, tour_steps, msg_dur, name=None, interval=0): """ Plays a Shepherd tour on the current website. """ instructions = "" for tour_step in tour_steps[name]: instructions += tour_step instructions += (""" // Start th...
Plays a Bootstrap tour on the current website. def play_bootstrap_tour( driver, tour_steps, browser, msg_dur, name=None, interval=0): """ Plays a Bootstrap tour on the current website. """ instructions = "" for tour_step in tour_steps[name]: instructions += tour_step instructions += ( ...
Plays an IntroJS tour on the current website. def play_introjs_tour( driver, tour_steps, browser, msg_dur, name=None, interval=0): """ Plays an IntroJS tour on the current website. """ instructions = "" for tour_step in tour_steps[name]: instructions += tour_step instructions += ( ...
Exports a tour as a JS file. It will include necessary resources as well, such as jQuery. You'll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs. def export_tour(tour_steps, name=None, filename="my_tour.js", url=None): """ ...
Clears the downloads folder. If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. def reset_downloads_folder(): ''' Clears the downloads folder. If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. ''' if os.path.exists(downloads_path) and not os.listdir(downloads_...
Returns whether the specified element selector is present on the page. @Params driver - the webdriver object (required) selector - the locator that is used (required) by - the method to search for the locator (Default: By.CSS_SELECTOR) @Returns Boolean (is element present) def is_element_presen...
Returns whether the specified element selector is visible on the page. @Params driver - the webdriver object (required) selector - the locator that is used (required) by - the method to search for the locator (Default: By.CSS_SELECTOR) @Returns Boolean (is element visible) def is_element_visibl...
Returns whether the specified text is visible in the specified selector. @Params driver - the webdriver object (required) text - the text string to search for selector - the locator that is used (required) by - the method to search for the locator (Default: By.CSS_SELECTOR) @Returns Boolean ...
Fires the hover event for the specified element by the given selector. @Params driver - the webdriver object (required) selector - the locator (css selector) that is used (required) by - the method to search for the locator (Default: By.CSS_SELECTOR) def hover_on_element(driver, selector, by=By.CSS_SEL...
Similar to hover_and_click(), but assumes top element is already found. def hover_element_and_click(driver, element, click_selector, click_by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): """ Similar to hover_and_click(), but assumes top element is al...
Searches for the specified element by the given selector. Returns the element object if the element is present on the page. The element can be invisible. Raises an exception if the element does not appear in the specified timeout. @Params driver - the webdriver object selector - the locator that...
Searches for the specified element by the given selector. Returns the element object if the element is present and visible on the page. Raises an exception if the element does not appear in the specified timeout. @Params driver - the webdriver object (required) selector - the locator that is use...
Finds all WebElements that match a selector and are visible. Similar to webdriver.find_elements. @Params driver - the webdriver object (required) selector - the locator that is used to search the DOM (required) by - the method to search for the locator (Default: By.CSS_SELECTOR) def find_visible_el...
Saves a screenshot to the current directory (or to a subfolder if provided) If the folder provided doesn't exist, it will get created. The screenshot will be in PNG format. def save_screenshot(driver, name, folder=None): """ Saves a screenshot to the current directory (or to a subfolder if provided) ...
Wait for and accept an alert. Returns the text from the alert. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds def wait_for_and_accept_alert(driver, timeout=settings.LARGE_TIMEOUT): """ Wait for and accept an alert. Returns the text from the aler...
Wait for and dismiss an alert. Returns the text from the alert. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds def wait_for_and_dismiss_alert(driver, timeout=settings.LARGE_TIMEOUT): """ Wait for and dismiss an alert. Returns the text from the a...
Wait for a browser alert to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.alert when the alert box may not exist yet. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds def wait_for_and_switch_to_alert...
Wait for an iframe to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.frame(). @Params driver - the webdriver object (required) frame - the frame element, name, or index timeout - the time to wait for the alert in seconds def switch_to_frame(driver, fra...
Wait for a window to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.window(). @Params driver - the webdriver object (required) window - the window index or window handle timeout - the time to wait for the window in seconds def switch_to_window(driver, ...
Use this to convert a url like this: https://blog.xkcd.com/2014/07/22/what-if-book-tour/ Into this: https://blog.xkcd.com def get_domain_url(url): """ Use this to convert a url like this: https://blog.xkcd.com/2014/07/22/what-if-book-tour/ Into this: https://blog.xkcd.com """ if...
A basic method to determine if a selector is an xpath selector. def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if (selector.startswith('/') or selector.startswith('./') or ( selector.startswith('('))): return True return ...
A basic method to get the link text from a link text selector. def get_link_text_from_selector(selector): """ A basic method to get the link text from a link text selector. """ if selector.startswith('link='): return selector.split('link=')[1] elif selector.startswith('link_text='): ...
Returns all unique links. Includes: "a"->"href", "img"->"src", "link"->"href", and "script"->"src" links. def _get_unique_links(page_url, soup): """ Returns all unique links. Includes: "a"->"href", "img"->"src", "link"->"href", and "script"->"src" links. """ if "http://" not in ...
Get the status code of a link. If the timeout is exceeded, will return a 404. For a list of available status codes, see: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes def _get_link_status_code(link, allow_redirects=False, timeout=5): """ Get the status code of a link. If t...
Finds all unique links in the html of the page source and then prints out those links with their status codes. Format: ["link" -> "status_code"] (per line) Page links include those obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". def _print_unique_links...
Decorator for implementing exponential backoff for retrying on failures. tries: Max number of tries to execute the wrapped function before failing. delay: Delay time in seconds before the FIRST retry. backoff: Multiplier to extend the initial delay by for each retry. max_delay: Max time in seconds to w...
This decorator limits how often a method can get called in a second. If the limit is exceeded, the call will be held in a queue until enough time has passed. Useful when trying to avoid overloading a system with rapid calls. def rate_limited(max_per_second): """ This decorator limits how of...
This decorator marks methods as deprecated. A warning is displayed if the method is called. def deprecated(message=None): """ This decorator marks methods as deprecated. A warning is displayed if the method is called. """ def decorated_method_to_deprecate(func): if inspect.isclass(func...
Connect to the IMAP mailbox. def imap_connect(self): """ Connect to the IMAP mailbox. """ self.mailbox = imaplib.IMAP4_SSL(self.imap_string, self.port) self.mailbox.login(self.uname, self.pwd) self.mailbox.select()
Searches for query in the given IMAP criteria and returns the message numbers that match as a list of strings. Criteria without values (eg DELETED) should be keyword args with KEY=True, or else not passed. Criteria with values should be keyword args of the form KEY="VALUE" where KEY is ...
This takes the result of imap_search and returns SANE results @Params result - result from an imap_search call @Returns List of IMAP search results def __parse_imap_search_result(self, result): """ This takes the result of imap_search and returns SANE results @Pa...
Given a message number that we found with imap_search, get the text/html content. @Params msg_nums - message number to get html message for @Returns HTML content of message matched by message number def fetch_html(self, msg_nums): """ Given a message number that ...
Given a message number that we found with imap_search, get the text/plain content. @Params msg_nums - message number to get message for @Returns Plaintext content of message matched by message number def fetch_plaintext(self, msg_nums): """ Given a message number...
Given a message number that we found with imap_search, fetch the whole source, dump that into an email object, and pick out the part that matches the content type specified. Return that, if we got multiple emails, return dict of all the parts. @Params msg_nums - message number to...
Get the html of an email, searching by subject. @Params email_name - the subject to search for @Returns HTML content of the matched email def fetch_html_by_subject(self, email_name): """ Get the html of an email, searching by subject. @Params email_name -...