INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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(selector, by=by) selector = self.__make_css_match_first_element...
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) remove_script = """jQuery('%s').remove()""" % select...
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! """ from bs4 import BeautifulSoup if not source: self.wait_for_ready_state_complete() source...
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 from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". """ page_url = self.get_current_url() soup = self.get_beautiful_soup(self.get_page_...
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 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 """ status_code...
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". """ links = self.get_unique_links() if multithreaded: from multiprocessing.dummy import Pool as Thre...
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 specified, will save it to the current folder. """ element = self.find_element(selector) element_png = element.screenshot_as_png ...
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, it's important that the jQuery library has been loaded first. This method will load jQuery if it wasn't already loaded. """ try: self.execute_script(script) exce...
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_with_status_codes(self): """ 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",...
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 length = 1.") if not os.path.exists(folder): ...
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 whatever you want. """ if not destination_folder: destination_folder = constants.Files.DOWNLOADS_FOLDER ...
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 destination folder. If no destination folder is specified, the default one is used. (The default downloads folder = "./downloaded_files") """ if not destination_folder: ...
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 name specified. If no destination folder is specified, the default one is used. (The default downloads folder = "./downloaded_files") """ if not destination_folder: ...
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...
def assert_no_js_errors(self): """ 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/is...
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...
def get_google_auth_password(self, totp_key=None): """ 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 ...
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, by): """ 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...
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: timeout = self.__get_new_timeout(timeout) if p...
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) self.set_value( ...
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, timeout=settings.LARGE_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...
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() (The longer version remains for backwards compatibility.) """ if self.timeout_multiplier and timeout ==...
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", timeout=settings.SMALL_TIMEOUT): """ Selects an HTML <select> option by specification. Option specifications are by "text", "index", or "value". ...
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, timeout=settings.SMALL_TIMEOUT): """ Selects an HTML <select> option by option text. @Params dropdown_selector - the <select> selector ...
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, creates a referral link there, and clicks on that link, which goes to the destination_page. (This generates real traffic for testing analytics software.) """ if not page_utils.is_vali...
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.sleep(0.05)
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...
def generate_referral_chain(self, pages): """ 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'...
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.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): """ 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 ma...
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 element must be visible (it cannot be hidden). """ if page_utils.is_xpath_selector(selector): ...
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: timeout = self.__get_new_timeout(timeout) ret...
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 nothing can be found. """ if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: ...
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: timeout = self.__get_new_timeout(timeout) ...
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(timeout) return self....
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...
def assert_exact_text(self, text, selector="html", by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): """ 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'...
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) return self.wait_for_link_text_visible(link...
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_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. """ if self.timeout_mul...
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_TIMEOUT: timeout = self.__get_new_timeout(timeout) ...
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_TIMEOUT): """ 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...
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, timeout=settings.LARGE_TIMEOUT): """ 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" st...
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_TIMEOUT): """ Similar to wait_for_element_absent() - returns nothing. As above, will raise an exception if the element stays present. Returns True if successful. Default tim...
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=settings.SMALL_TIMEOUT): """ Similar to wait_for_element_not_visible() - returns nothing. As above, will raise an exception if the element stays visible. Returns True if successf...
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) page_actions.switch_to_frame(self.driver, frame, t...
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(len(self.driver.window_handles) - 1)
*** 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...
def check_window(self, name="default", level=0, baseline=False): """ *** 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, ...
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 ...
def get_new_driver(self, browser=None, headless=None, servername=None, port=None, proxy=None, agent=None, switch_to=True, cap_file=None, disable_csp=None): """ This method spins up an extra browser for tests that require more than one. The first browser ...
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 was an exception that occurred during the test, assuming that the exception was in a try/except block and not thrown. """ exception_info = sys.exc_info()[1] if hasattr(excep...
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.ceil(timeout_multiplier * timeout)) ...
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...
def __get_improved_exception_message(self): """ 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-sen...
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.append( "CHECK #%s: (%s)\n %s" % ( sel...
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_TIMEOUT): """ 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 a...
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=settings.MINI_TIMEOUT): """ 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...
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...
def process_delayed_asserts(self, print_only=False): """ 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 ...
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) css_selector = re.escape(css_selector) css_selec...
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.select('[class*=HeaderMenu]'): drop_down_list.appe...
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 add the following line to the subclass setUp() method: super(SubClassOfBaseCase, self).setUp() """ self.masterqa_mode = masterqa_mode self.is_pytest = N...
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 log files """ if not self.__last_page_screenshot and ( not self.__last_page_screenshot_png): try: ...
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) content_type = "text/plain" if file_name.endswith(".html"): content_typ...
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_uploaded_files = list(set(already_uploaded_files)) already_uploaded_files.sort() file...
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.BootstrapTour.MIN_JS verify_script = ("""// Verify Bootstrap Tour activated ...
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.Hopscotch.MIN_JS backdrop_style = style_sheet.hops_backdrop_style verify_script = ("""// ...
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 = ("""// Verify IntroJS activated var intro2 = introJs(); ...
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_arrows_css = constants.Shepherd.THEME_ARROWS_CSS sh_theme_arrows_fix_css = constants.Shepherd.THEME_ARR_...
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 the tour tour.start(); $tour = to...
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 += ( """]); // Initialize the tour ...
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 += ( """] }); intro.setOption("di...
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): """ 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. "...
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_path) == []: archived_downloads_folder = os.path.join(downloads_path, '..', ...
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_present(driver, selector, by=By.CSS_SELECTOR): """ 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_SELE...
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_visible(driver, selector, by=By.CSS_SELECTOR): """ 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_SELE...
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 ...
def is_text_visible(driver, text, selector, by=By.CSS_SELECTOR): """ 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 t...
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_SELECTOR): """ 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...
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 already found. """ start_ms = time.time() * 1000.0 stop_ms = st...
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...
def wait_for_element_present(driver, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ 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 excepti...
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...
def wait_for_element_visible(driver, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ 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 ...
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_elements(driver, selector, by=By.CSS_SELECTOR): """ 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 met...
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) If the folder provided doesn't exist, it will get created. The screenshot will be in PNG format. """ if "." not in name: name = name + ".png" if folder: ...
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 alert. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds """ alert = wait_for_and_switch_to_alert(driver, time...
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 alert. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds """ alert = wait_for_and_switch_to_alert(driver, ti...
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(driver, timeout=settings.LARGE_TIMEOUT): """ 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) ...
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, frame, timeout=settings.SMALL_TIMEOUT): """ 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 time...
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, window, timeout=settings.SMALL_TIMEOUT): """ 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 t...
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 "http://" not in url and "https://" not in url: return url url_header = url.split('://')[0] simple_url = url.split(':/...
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 False
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='): return selector.split('link_text=')[1] return selector
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 page_url and "https://" not in page_url: return [] prefix = 'http:' if page_url.startswith('https:'): ...
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 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 """ status_code = None try: ...
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_with_status_codes(page_url, soup): """ 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"->"...
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...
def retry_on_exception(tries=6, delay=1, backoff=2, max_delay=32): ''' 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 exte...
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 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. """ min_interval = 1.0 / ...
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): # Handle a deprecated class differently from a deprecated method msg = "Cl...
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 ...
def __imap_search(self, ** criteria_dict): """ 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 ...
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 @Params result - result from an imap_search call @Returns List of IMAP search results """ if isinstance(result, types.ListType): # A...
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 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 """ if not ms...
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 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 """ if ...
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...
def __imap_fetch_content_type(self, msg_nums, content_type): """ 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, r...
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 - the subject to search for @Returns HTML content of the matched email """ if not email_name: raise EmailException("Subject cann...
Get the plain text of an email, searching by subject. @Params email_name - the subject to search for @Returns Plaintext content of the matched email
def fetch_plaintext_by_subject(self, email_name): """ Get the plain text of an email, searching by subject. @Params email_name - the subject to search for @Returns Plaintext content of the matched email """ if not email_name: raise EmailExcepti...
Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to return @Returns Content of the matched email in the given content type
def search_for_recipient(self, email, timeout=None, content_type=None): """ Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to ...
Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to return @Returns Content of the matched email in the given content type
def search_for_subject(self, subject, timeout=None, content_type=None): """ Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to ...