# locate submit button by_xpath sign_in_button = driver.find_element_by_xpath('//*[@type="submit"]') # .click() to mimic button click sign_in_button.click() sleep(0.5) # driver.get method() will navigate to a page given by the URL address driver.get('https://www.google.com') sleep(3) # locate search form by_name search_query = driver.find_element_by_name('q') # send_keys() to simulate the search text key strokes search_query.send_keys(parameters.search_query) sleep(0.5) # navigate to the URL address specified by search_query in parameters.py #driver.get(parameters.search_query) # .send_keys() to simulate the return key search_query.send_keys(Keys.RETURN) sleep(3) # locate URL by_class_name linkedin_urls = driver.find_elements_by_class_name('iUh30')
def order(shop=None, browser=None, lego_set=None, order_list=None, username=None, password=None): """ Fill in LEGO parts to be ordered in LEGO's customer service shop. """ from selenium.common.exceptions import NoSuchElementException from selenium.webdriver import Chrome, Firefox from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait from time import sleep order_list = order_list.split(',') shop_url = 'https://wwwsecure.us.lego.com/{shop}/service/replacementparts/order'.format(shop=shop) browser = Chrome() if browser == 'chrome' else Firefox() browser.get(shop_url) print("Sometimes they ask you to fill in a survey.") try: survey_layer = browser.find_element_by_id('ipeL104230') survey_layer.send_keys(Keys.ESCAPE) except NoSuchElementException: print("We're lucky, no survey on the LEGO shop today!") print("They want to know how old we are.") age_field = browser.find_element_by_name('rpAgeAndCountryAgeField') age_field.send_keys('55') age_field.send_keys(Keys.RETURN) if username and password: print("Let's log in with LEGO ID {user}.".format(user=username)) login_link = browser.find_element_by_css_selector('.legoid .links > a') login_link.click() browser.switch_to.frame('legoid-iframe') user_input = browser.find_element_by_id('fieldUsername') user_input.click() user_input.send_keys(username) passwd_input = browser.find_element_by_id('fieldPassword') passwd_input.click() passwd_input.send_keys(password) login_button = browser.find_element_by_id('buttonSubmitLogin') login_button.click() browser.switch_to.default_content() sleep(4) # seconds wait = WebDriverWait(browser, 5) print("We need to tell them which set we want to buy parts from: {lego_set}".format(lego_set=lego_set)) setno_field = wait.until(EC.element_to_be_clickable( (By.CSS_SELECTOR, '.product-search input[ng-model=productNumber]'))) setno_field.send_keys(lego_set) setno_field.send_keys(Keys.RETURN) print("Let's scroll the page down a bit, so we can see things better.") browser.execute_script("window.scroll(0, 750);") print("That's gonna be crazy: {count} elements to order! Let's rock.".format(count=len(order_list))) element_field = wait.until(EC.element_to_be_clickable( (By.ID, 'element-filter'))) print() for brick in order_list: part_no, quantity = brick.split(':') print("- {qty}x #{pn} ".format(qty=quantity, pn=part_no), end='') element_field.clear() element_field.send_keys(part_no) element_field.send_keys(Keys.RETURN) sleep(.3) # seconds try: add_button = browser.find_element_by_css_selector('.element-details + button') add_button.click() sleep(.2) # seconds except NoSuchElementException: print("OOOPS! No LEGO part with that number found in set #{set}. :-(".format(set=lego_set)) continue try: warn_msg = browser.find_element_by_css_selector('.alert-warning .sold-out-info') if warn_msg.is_displayed(): print("NOTE: item out of stock. ", end='') add_anyway = browser.find_element_by_css_selector('.alert-warning + .clearfix button') add_anyway.click() except NoSuchElementException: pass amount_select = browser.find_elements_by_css_selector('.bag-item select')[-1] amount_select.send_keys(quantity) amount_select.send_keys(Keys.TAB) selected = Select(amount_select).first_selected_option if quantity != selected.text: print("WARNING: Could not select desired quantity. {} != {}".format(quantity, selected.text)) else: print() browser.execute_script("window.scroll(0, 0);") print() print("We're done. You can finalize your order now. Thanks for watching!")
print("Height didn't update") if (toBottom): break else: toBottom = True last_height = new_height if __name__ == "__main__": openBrowser = True try: pathFile = open("pathFile.txt", "r") driver = Chrome(pathFile.readline()) pathFile.close() driver.get(WEBSITE_URL) searchBar = driver.find_element_by_name("searchKeyword") except Exception: openBrowser = False keyword = "" try: if not openBrowser: raise Exception("No path to the selenium web driver") keyword = sys.argv[1] searchBar.send_keys(keyword) searchBar.send_keys(Keys.ENTER) except IndexError: openBrowser = False driver.close()
class Browser: def __init__(self): pass def start(self, headless=False, proxy=None, user_agent=None): global driver chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") chrome_options.add_argument("--disable-dev-shm-using") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--lang=en") # if os.environ.get('ARE_ON_TRAVIS') == 'True': # chrome_options.add_argument("--no-sandbox") # chrome_options.add_argument("--disable-gpu") if headless: chrome_options.add_argument("--headless") if proxy: proxy = json.loads(proxy) manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "Chrome Proxy", "permissions": [ "proxy", "tabs", "unlimitedStorage", "storage", "<all_urls>", "webRequest", "webRequestBlocking" ], "background": { "scripts": ["background.js"] }, "minimum_chrome_version":"22.0.0" } """ background_js = """ var config = { mode: "fixed_servers", rules: { singleProxy: { scheme: "http", host: "%s", port: parseInt(%s) }, bypassList: ["localhost"] } }; chrome.proxy.settings.set({value: config, scope: "regular"}, function() {}); function callbackFn(details) { return { authCredentials: { username: "******", password: "******" } }; } chrome.webRequest.onAuthRequired.addListener( callbackFn, {urls: ["<all_urls>"]}, ['blocking'] ); """ % (proxy['host'], proxy['port'], proxy['user'], proxy['pass']) pluginfile = 'proxy_auth_plugin.zip' with zipfile.ZipFile(pluginfile, 'w') as zp: zp.writestr("manifest.json", manifest_json) zp.writestr("background.js", background_js) chrome_options.add_extension(pluginfile) chrome_options.add_argument('--proxy-server=%s' % proxy) # chrome_options.add_argument('--proxy-server=%s' % hostname + ":" + port) if user_agent: chrome_options.add_argument('--user-agent=%s' % user_agent) self.driver = Chrome(options=chrome_options) def stop(self): self.driver.quit() def get_driver(self): return self.driver def wait_page_loaded(self): def condition(browser): return self.driver.execute_script( "return document.readyState") in ["complete" or "loaded"] try: wait = WebDriverWait(self.driver, timeout) result = wait.until(condition) except TimeoutException: return False return result def wait_until_element_exists(self, by, value): if by == 'xpath': elem = WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located((By.XPATH, value))) elif by == 'id': elem = WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located((By.ID, value))) elif by == 'name': elem = WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located((By.NAME, value))) elif by == 'css': elem = WebDriverWait(self.driver, timeout).until( EC.presence_of_element_located((By.CSS_SELECTOR, value))) return elem def select_dropdown_by(self, by, value): if by == 'xpath': elem = Select(self.driver.find_element_by_xpath(value)) elif by == 'id': elem = Select(self.driver.find_element_by_id(value)) elif by == 'name': elem = Select(self.driver.find_element_by_name(value)) elif by == 'css': elem = Select(self.driver.find_element_by_css_selector(value)) return elem
class NewTrainingData(StaticLiveServerTestCase) : def setUp(self) : self.browser = Chrome() self.browser.implicitly_wait(3) self.first_training_session = log.testdata.get_first_training_session_in_text_form() self.second_training_session = log.testdata.get_second_training_session_in_text_form() def tearDown(self) : self.browser.quit() def user_sees_inputfields_and_enters_data(self, data) : '''checks if inputfields are there and enters data in them - data is a dictionary, keys are the same as the names used in the html form''' # user sees that the page is divided in 2 parts, a part for input of a # training session, and a part that displays previous inputted sessions in a # table. # in the input part, user sees: # a date edit box date_editbox = self.browser.find_element_by_name('date') self.assertIsNotNone(date_editbox) # a distance edit box distance_editbox = self.browser.find_element_by_name('distance') self.assertIsNotNone(distance_editbox) # an average HR edit box average_heart_rate_editbox = self.browser.find_element_by_name('average_heart_rate') self.assertIsNotNone(average_heart_rate_editbox) # a planned type of training select box planned_type_of_training_select = Select(self.browser.find_element_by_name('planned_type_of_training')) self.assertIsNotNone(planned_type_of_training_select) # an executed time edit box executed_time_editbox = self.browser.find_element_by_name('executed_time') self.assertIsNotNone(executed_time_editbox) # an in zone edit box in_zone_editbox = self.browser.find_element_by_name('in_zone') self.assertIsNotNone(in_zone_editbox) # a planned duration edit box planned_duration_editbox = self.browser.find_element_by_name('planned_duration') self.assertIsNotNone(planned_duration_editbox) # a notes textarea notes_textarea = self.browser.find_element_by_name('notes') self.assertIsNotNone(notes_textarea) # user sees a submit button with the text 'Save' on it submit_button = self.browser.find_element_by_id('submit_button') self.assertEqual(submit_button.get_attribute('value'), 'Save') # user enters data in the 4 fields an presses submit # TODO : user sees he gets redirected to the same home url date_editbox.send_keys(data['date']) distance_editbox.send_keys(data['distance']) average_heart_rate_editbox.send_keys(data['average_heart_rate']) planned_type_of_training_select.select_by_visible_text(data['planned_type_of_training']) executed_time_editbox.send_keys(data['executed_time']) in_zone_editbox.send_keys(data['in_zone']) planned_duration_editbox.send_keys(data['planned_duration']) notes_textarea.send_keys(data['notes']) submit_button.submit() def check_entered_row_of_data_on_screen(self, row_to_check, data) : ''' checks one training session of data entered - data is a dictionary with keys same as names used in the html form. the row to check is 1-based, the array of rows is 0 based. but this is not a problem, since the table_row[0] is the header row, and we are not going to check that one. ''' table_rows = self.browser.find_elements_by_tag_name('tr') data_elements = data.values() # for table_row in table_rows : self.assertGreater(len(table_rows), row_to_check, 'table only has ' + str(len(table_rows)) + ' rows and you wanted to check row ' + str(row_to_check)) for element in data_elements : self.assertTrue(element in table_rows[row_to_check].text, element + ' not in ' + table_rows[row_to_check].text) def test_enter_training_data(self) : # user gets the url self.browser.get(self.live_server_url) # user enters a first set of data and checks if the data is receptioned by the system self.user_sees_inputfields_and_enters_data(self.first_training_session) # user sees the row in the table on the page matching the data entered self.check_entered_row_of_data_on_screen(1, self.first_training_session) # user enters a second set of data checks if the data is receptioned by the system self.user_sees_inputfields_and_enters_data(self.second_training_session) # user sees both rows in the table on the page matching the data from the second training session self.check_entered_row_of_data_on_screen(1, self.first_training_session) self.check_entered_row_of_data_on_screen(2, self.second_training_session) # user closes the browser and reopens, to see his previously entered data self.browser.quit() self.browser = Chrome() self.browser.implicitly_wait(3) # user gets the url self.browser.get(self.live_server_url) self.check_entered_row_of_data_on_screen(1, self.first_training_session) self.check_entered_row_of_data_on_screen(2, self.second_training_session) def test_web_page_is_loaded(self) : # user gets the url self.browser.get(self.live_server_url) # user sees the title in the browser window self.assertIn('Runners Log', self.browser.title) def test_css_is_used(self) : # user sees the table layout of the input elements # The "add training" part of the website is put in a table layout, 3 x 3. The "Distance" label needs to have # a different x location than the "Date" label. The "Date" label is in column 1, the "Distance" label is in # column 2. If the css should not be used, these labels would have the same x location, thus failing the # test. self.browser.get(self.live_server_url) labels = self.browser.find_elements_by_class_name('label') for label in labels : if label.text == 'Distance' : distance_x = label.location['x'] if label.text == 'Date' : date_x = label.location['x'] self.assertNotEqual(date_x, distance_x, 'label \'Date\' and label \'Distance\' have the same x-coordinate - CSS possibly not loaded')
class WebPage(Engine): def __init__(self, executable_path): super(WebPage, self).__init__() self._url = None self._executable_path = executable_path self._driver = None def start(self): self._driver = Chrome(executable_path=self._executable_path) self._driver.maximize_window() if self._url is not None: self._driver.get(self._url) Logger.info(self, 'Engine started') def stop(self): self._driver.close() self._driver = None Logger.info(self, 'Engine stopped') def _find_element_by_id(self, id): return self._driver.find_element_by_id(id) def _find_element_by_xpath(self, xpath): return self._driver.find_element_by_xpath(xpath) def _find_element_by_class_name(self, class_name): return self._driver.find_element_by_class_name(class_name) def _find_elements_by_class_name(self, class_name): return self._driver.find_elements_by_class_name(class_name) def _find_element_by_name(self, name): return self._driver.find_element_by_name(name) def _find_element_by_link_text(self, link_text): return self._driver.find_element_by_link_text(link_text) def _wait_for_element_by_xpath(self, xpath, timeout=5): WebDriverWait(self._driver, timeout).until( EC.presence_of_element_located((By.XPATH, xpath))) def _wait_for_element_by_class_name(self, class_name, timeout=0.5): WebDriverWait(self._driver, timeout).until( EC.presence_of_element_located((By.CLASS_NAME, class_name))) return self._driver.find_element_by_class_name(class_name) def _wait_for_visibility_by_xpath(self, xpath, timeout=5): WebDriverWait(self._driver, timeout).until( EC.visibility_of_element_located((By.XPATH, xpath))) def _wait_for_clickability_by_xpath(self, xpath, timeout=5): WebDriverWait(self._driver, timeout).until( EC.element_to_be_clickable((By.XPATH, xpath))) def _wait_for_frame_availability_by_xpath(self, xpath, timeout=5): WebDriverWait(self._driver, timeout).until( EC.frame_to_be_available_and_switch_to_it((By.XPATH, xpath))) def _switch_to_frame(self, frame_web_element): self._driver.switch_to.frame(frame_web_element) @except_to_bool(exc=(NoAlertPresentException, TimeoutException)) def _is_alert_present(self, timeout=0.1): WebDriverWait(self._driver, timeout).until(EC.alert_is_present()) def _back(self): self._driver.back() sleep(1)
while running: while start: if datetime.now() >= open_time: # This triggers at the start time # This way it will open the browser ahead of time so you # can fill in the info. # Instantiate the brower instance browser = Chrome(options=opts) # Navigate to the survey url browser.get(survey_url) # Grabs ahold of the survey form for later. application_form = browser.find_element_by_name("surveyForm") # # These are just for testing. I got tired of typing them in manually. # # Uncomment as needed. first_input = browser.find_elements_by_tag_name("input")[0] first_input.send_keys(name_input) second_input = browser.find_elements_by_tag_name("textarea")[0] second_input.send_keys(number_input) # Set the start bool to True to let the program know we've opened # the form and are waiting for the submit time start = False while not submit: if datetime.now() >= submit_time: # This triggers at the submit time