def read_string(prompt="Please Enter a String: ", max=20, min=1, side='|', sep=' ', delimiter=' ', width=80): """Prompts user for string and only accepts a string within a certain length. Then returns the users text. Args: prompt: Text that is prompted to user. DEFAULT: 'Please Enter a String: ' max: Maximum length text length. DEFAULT: 20 min: Minimum length text length. DEFAULT: 1 side: Character used to print as the border. DEFAULT: | sep: Character used to separate the text and the side. DEFAULT: ' ' delimiter: Character used to fill the empty space or white space. DEFAULT: ' ' width: DEFAULT: 80""" # Loop until correct input is given while True: pyprint.__prompt(prompt, side, sep, delimiter, width) user_input = input("") # If string is longer than max if len(user_input) > max: pyprint.write("Input is to long. Please enter less than", max, "characters.", side=side, sep=sep, delimiter=delimiter, width=width) elif len(user_input) < min: pyprint.write("Input is to short. Please enter more than", min, "characters.", side=side, sep=sep, delimiter=delimiter, width=width) # If string is smaller or equal to max in length else: break return user_input
def load(self, url: str, tab_name: str, tab=0): """Loads a new page in the given tab. If the tab number is -1 then it will load the page in a new tab. Reopens Browser if it is closed. Args: url: Page Url that will be loaded. tab_name: Tab name for the url page. tab: The tab to load page on. DEFAULT: 0""" if not self.tab_names: self.tab_names.append(tab_name) if not self.open: self.__init__() if tab is -1: # Loads page to a new tab self.new_tab(url, tab_name) elif tab is not self.current_tab: self.switch_tab(tab) # Will set the current tab variable self.load(url, tab_name, self.current_tab) else: self.urls[tab] = url self.tab_names[tab] = tab_name self.browser.get(url) pyprint.write("Loading URL:", url) pyprint.center(tab_name, "Loaded") self.__print()
def get_to_items(browser: FireBrowser): browser.click('#pos', sleep_time=0) browser.click('#inventory') browser.click('button', '100', sleep_time=4) part_list = Parts() url = "" while browser.check_selector('a', 'Next') and url is not browser.url(): el_list = browser.get_elements('.table tr') el_list.pop(0) for el_item in el_list: info = browser.get_elements('td', el_item) """ 2: item_name 1: item_number 4: available 5: reserved 6: intransit 9: avg_cost 11: Avg_cons 10: reorder""" part_list.add_item_convert([ info[2].text, info[1].text, info[4].text, info[5].text, info[6].text[-1:], info[9].text, info[11].text, info[10].text ]) pyprint.write(part_list.last_item().save_string()) browser.click('.next > a:nth-child(1)') url = browser.url() return part_list
def run(browser: FireBrowser): """Given a FireBrowser object will then check to see if there are notifications then will go through the list and respond appropriately to them. Args: browser: FireBrowser Object""" midline("STATUS UPDATING") if browser.find_tab("Portal") is not -1: browser.switch_tab("Portal") elif not browser.tab_names: login.run(browser) else: login.run(browser) file = FileHandle("status") data = file.read_to_data() browser.remind_me_later() if browser.check_selector(data['notify_check']): write("Looking at Notifications...") while delete_notifications(browser, data): browser.click(data['notify_dropdown_click']) while __find_updateable_notification(browser, data): """Check to see if asurion or if appointment.""" browser.click(data['lead_textarea']) headings = browser.get_elements_text(data['lead_type_heading']) if contain_list("Appointment", headings): browser.click(data['status_select']) browser.click(data['status_select_awaiting']) browser.send_text(data['appointment_text'], 'lead_textarea') elif contain_list("Asurion", headings): browser.send_text(data['asurion_text'], 'lead_textarea')
def run(browser: FireBrowser): """Given a FireBrowser object will then load the appropriate file to get username and password to login in to UBIF Portal site. Args: browser: FireBrowser Object""" midline("LOGIN") if browser.find_tab("Portal") is not -1: browser.switch_tab("Portal") elif not browser.tab_names: browser.load("https://portal.ubif.net/login", "Portal") else: browser.new_tab("https://portal.ubif.net/login", "Portal") file = FileHandle("login") data = file.read_to_data() if browser.check_selector(data['login_css_click']): write("Logging in...") browser.click(data['login_css_click'], sleep_time=4) browser.send_text(data['username'], data['username_css_text']) browser.click(data['username_css_click']) browser.send_text(data['password'], data['password_css_text']) browser.click(data['password_css_click'], sleep_time=4) browser.remind_me_later() midline("LOGGED IN") else: midline("ALREADY LOGGED IN")
def save_string(self) -> str: gadget_string = "" for string in self.gadget_numbers: gadget_string += str(string) + "+" string = (self.name + "," + str(self.item_number) + "," + str(self.available) + "," + str(self.reserved) + "," \ + str(self.transit) + "," + str(self.avg_cost) + "," + str(self.avg_cons) + "," + str(self.reorder) \ + "," + gadget_string[:-1] + "," + self.qsc_number) write(string) return str(string)
def __find_updateable_notification(browser: FireBrowser, data: dict) -> bool: noti_list = data['update_noti'].split[','] write("Updating Notifications...") browser.click(data['notify_dropdown_click']) for element in browser.get_elements(data['notify_message']): if contain_list(element.text, noti_list): browser.click(element) return True return False
def remind_me_later(self): """Checks to see if the Remind Me Later button is on the screen and clicks it.""" buttons = self.get_elements("button.show") while buttons: pyprint.write("Remind Me Later") if len(buttons) > 1: self.click(buttons[len(buttons) - 1]) else: self.click(buttons[0]) buttons = self.get_elements("button.show")
def __print(self): pyprint.midline("BROWSER DATA", mid=":") # pyprint.center(":::TAB NAMES:::") # pyprint.write(self.tab_names) # pyprint.center(":::URLS:::") # pyprint.write(self.urls) # pyprint.midline() pyprint.write("Current Working Tab:", self.tab_names[self.current_tab]) pyprint.write("Total Amount of Tabs:", len(self.urls)) pyprint.midline(mid='#')
def delete(self): """Deletes the file and returns if it was able to delete the file.""" if not self.created() and self.doc.closed: try: write("Deleting File...") remove(self.get_full_path()) return True except OSError: warning("Unable to Delete file: ", self.get_full_path()) return False
def save(self): """Saves the list of items to a file on the computer""" pyprint.write("Saving Item List...") item_file = FileHandle('items') item_file.create() item_strings = [] for it in self.items: item_strings.append(it.save_string()) item_file.write_list(item_strings) pyprint.write("Item List Saved")
def find_tab(self, tab_name: str): """Finds the tab with the tab name given and returns the tab number. If tab can't be found then returns -1. Args: tab_name: Tab name to find.""" pyprint.write("Finding Tab:", tab_name) for i in range(0, len(self.tab_names)): if tab_name is self.tab_names[i]: return i return -1
def delete_notifications(browser: FireBrowser, data: dict) -> bool: noti_list = data['delete_noti'].split[','] write("Deleting Extra Notifications...") browser.click(data['notify_dropdown_click']) check = False for element in browser.get_elements(data['notify_message']): if contain_list(element, noti_list): browser.click( browser.get_element(data['notify_delete'], element=element)) check = True return check
def write_list(self, message) -> bool: if self.created() and self.doc.closed: try: write("Writing to File...") self.doc = open(self.get_full_path(), 'w') for line in message: self.doc.write(line + '\n') self.doc.close() return True except OSError: warning("Could not find or open file ", self.get_full_path()) return False
def switch_tab(self, tab): """Sets the current tab to a new tab using either tab name or tab number. Args: tab: The tab to go to.""" if self.open: pyprint.write("Changing Tab...") if type(tab) is str: tab = self.find_tab(tab) if tab is not self.current_tab: self.current_tab = tab self.browser.switch_to.window(self.browser.window_handles[tab])
def read(self) -> list: """Reads text from the file and returns array of strings. If unable to open file will print to user and return None""" if self.created(): try: write("Reading File...") lines = [] self.doc = open(self.get_full_path(), 'r') for line in self.doc: lines.append(line.split('\n')[0]) self.doc.close() return lines except OSError: warning("Could not find or open ", self.get_full_path()) return []
def __init__(self): pyprint.midline("FIREFOX") pyprint.write("Loading Selenium...") pyprint.write("Setting up browser...") self.urls = [""] fapa = DesiredCapabilities.FIREFOX fapa["pageLoadStrategy"] = "none" fp = webdriver.FirefoxProfile() fp.set_preference("browser.tabs.remote.autostart", False) fp.set_preference("browser.tabs.remote.autostart.1", False) fp.set_preference("browser.tabs.remote.autostart.2", False) self.browser = webdriver.Firefox(firefox_profile=fp, desired_capabilities=fapa) self.tab_names = [] self.current_tab = 0 self.open = True self.wait = WebDriverWait(self.browser, 20)
def write(self, *messages) -> bool: """Opens and writes given data to the file as text. Will print to the user if were unable to write to the file and return if we were able to write to file. Args: messages: Takes in multiple objects and strings.""" if self.created() and self.doc.closed: try: write("Saving File...") self.doc = open(self.get_full_path(), 'w') for line in list(messages): self.doc.write(str(line) + '\n') self.doc.close() return True except OSError: warning("Could not find or open file ", self.get_full_path()) return False
def create(self, filename="", ext="ini", location=""): """Tries to create the file and the returns if the file has been created or not. if Attributes are given it will open or try to create a new file Attributes: filename: Filename to create without extension. ext: The type of text file being created. Will Default to ini location: The location on HDD to look ie C://... Will Default to location where program is running.""" if filename: self.filename = filename self.ext = ext self.location = location try: write("Creating File...") self.doc = open(self.get_full_path(), "a") self.doc.close() return True except OSError: warning("Could not open: ", self.get_full_path()) return False
def read_number(prompt="Please Enter a Number: ", max=10, min=0, side='|', sep=' ', delimiter=' ', width=80): """Prompts user for input and will only except an integer that fits within the max and min range given. Then returns the given input. Args: prompt: Texts that is prompted to user. DEFAULT: 'Please Enter a Number: ' max: The highest integer that will be accepted. DEFAULT: 10 min: The lowest integer that will be accepted. DEFAULT: 0 side: Character used to print as the border. DEFAULT: | sep: Character used to separate the text and the side. DEFAULT: ' ' delimiter: Character used to fill the empty space or white space. DEFAULT: ' ' width: DEFAULT: 80""" # Loop until Correct Input is given while True: pyprint.__prompt(prompt, side, sep, delimiter, width) user_input = input("") # If user input is an integer try: user_input = int(user_input) if user_input > max: pyprint.write("Please enter a number less than", max, side=side, sep=sep, delimiter=delimiter, width=width) elif user_input < min: pyprint.write("Please enter a number larger than", min, side=side, sep=sep, delimiter=delimiter, width=width) else: # Number is between min and max so stop the loop break # If user input is not an integer except ValueError: pyprint.write(user_input, "is not an integer.") return user_input
def new_tab(self, url="", tab_name=""): """Creates a new tab blank tab at the end of the list and Returns the number of the new tab. If given a URL and tab name then will load that into the new tab. Args: url: URL to load. DEFAULT: blank tab_name: Tab name of new tab. DEFAULT: blank""" if self.open: pyprint.write("Creating new tab...") self.browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') self.browser.switch_to.window(self.browser.window_handles[len(self.urls)]) if url and tab_name: self.urls.append(url) self.tab_names.append(tab_name) self.current_tab = len(self.urls) - 1 self.load(url, tab_name, self.current_tab) else: self.urls.append("") self.tab_names.append("") self.current_tab = len(self.urls) - 1 return self.current_tab
def pretty_print(self): midline(str(self.item_number)) write('SKU:', self.item_number) write('Name:', self.name) write('Available:', self.available) write('Reserved:', self.reserved) write('Transit:', self.transit) write('Average Cost: $', self.avg_cost) write('Average Consumption:', self.avg_cons) write('Reorder Level:', self.reorder)