我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.webdriver.common.keys.Keys.ENTER。
def linkedin_search(): linkedin_login() time.sleep(2) x = driver.find_element_by_class_name('type-ahead-input') search = x.find_element_by_tag_name('input') search.send_keys('harvard') search.send_keys(Keys.ENTER) time.sleep(8) new_url = (driver.current_url).replace('index', 'schools') new_url = new_url.replace('GLOBAL_SEARCH_HEADER', 'SWITCH_SEARCH_VERTICAL') driver.get(new_url) time.sleep(5) driver.find_element_by_css_selector('#ember1790').click() time.sleep(5) x = driver.find_element_by_class_name('company-actions-bar') x.find_element_by_tag_name('a').click() time.sleep(5) start_year = driver.find_element_by_id('alumni-search-year-start') end_year = driver.find_element_by_id('alumni-search-year-end') start_year.send_keys('2014') start_year.send_keys(Keys.ENTER) time.sleep(3) list_of_people = driver.find_elements_by_class_name('org-alumni-profiles-module__profiles-list-item') for i in list_of_people: print(i.text)
def login(self, email, password): """Log to facebook using email (str) and password (str)""" url = "https://mbasic.facebook.com" self.get(url) email_element = self.find_element_by_name("email") email_element.send_keys(email) pass_element = self.find_element_by_name("pass") pass_element.send_keys(password) pass_element.send_keys(Keys.ENTER) try: self.find_element_by_name("xc_message") print("Logged in") return True except NoSuchElementException as e: print("Fail to login") return False
def postImageInGroup(self, url, text, image1, image2="", image3=""): """Post image(str) in a group(url:str) with the text(str), doesn't work in phantomJS""" self.get(url) v = self.find_element_by_name("view_photo") v.send_keys(Keys.ENTER) self.save_screenshot("debug.jpg") i1 = self.find_element_by_name("file1") i2 = self.find_element_by_name("file2") i3 = self.find_element_by_name("file3") i1.send_keys(image1) i2.send_keys(image2) i3.send_keys(image3) filter = self.find_element_by_name("filter_type") filter.value_of_css_property(0) pre = self.find_element_by_name("add_photo_done") pre.click() m = self.find_element_by_name("xc_message") m.send_keys(text) vp = self.find_element_by_name("view_post") vp.click() return True
def test_cannot_add_duplicate_items(self): # Edith goes to the home page and starts a new list self.browser.get(self.live_server_url) self.get_item_input_box().send_keys('Buy wellies') self.get_item_input_box().send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy wellies') # She accidentally tries to enter a duplicate item self.get_item_input_box().send_keys('Buy wellies') self.get_item_input_box().send_keys(Keys.ENTER) # She sees a helpful error message self.wait_for(lambda: self.assertEqual( self.browser.find_element_by_css_selector('.has-error').text, "You've already got this in your list" ))
def test_layout_and_styling(self): # Edith goes to the home page self.browser.get(self.live_server_url) self.browser.set_window_size(1024, 768) # She notices the input box is nicely centered inputbox = self.get_item_input_box() self.assertAlmostEqual( inputbox.location['x'] + inputbox.size['width']/2, 512, delta=10 ) # She starts a new list and sees the input is nicely # centered there too inputbox.send_keys('testing') inputbox.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: testing') inputbox = self.get_item_input_box() self.assertAlmostEqual( inputbox.location['x'] + inputbox.size['width']/2, 512, delta=10 )
def test2(): print ('nothing') print ('12sdfas3') elem = a1.driver.find_element_by_id("editArea") print ('12sdfas31112') #???????? b=str(datetime.datetime.now()) b=qiushi.main1() print (b) elem.send_keys(b) print ('1') time.sleep(2000) elem.send_keys(Keys.ENTER) print ('2')
def hacker_typing(browser, spinter_selection, code): """We need to break Splinter abstraction and fall back to raw Selenium here. Note: There is a bug of entering parenthesis due to IPython capturing keyboard input. http://stackoverflow.com/questions/22168651/how-to-enter-left-parentheses-into-a-text-box """ elem = spinter_selection[0]._element driver = browser.driver # Activate IPython input mode ActionChains(driver).click(elem).send_keys(Keys.ENTER).perform() # Type in the code a = ActionChains(driver) a.send_keys(code) a.perform() time.sleep(1.0) # Execute the text we just typed a = ActionChains(driver) a.key_down(Keys.SHIFT).send_keys(Keys.ENTER).key_up(Keys.SHIFT) a.perform()
def fill_form(self, fields=(), submit=True): """ Fill in a form and press enter on last :param fields: list of tupules: (input_id, value), (input_id, value) :return: """ elem = None for input_id, value in fields: if '//' in input_id: find = input_id else: find = "//input[@id='{id}']".format(id=input_id) elem = self.find_element(find) if elem.tag_name == 'select': select = Select(elem) select.select_by_visible_text(value) else: elem.send_keys(value) if elem and submit: elem.send_keys(Keys.ENTER)
def open(driver: webdriver, group: str, element: str): """Open specific element that belongs to the group. NOTE: Some browsers (Firefox & IE) can cause problems when dealing with JS menus. In order to move the cursor to the correct menu element before clicking on it, the driver needs to be instructed to move the cursor to a visible menu element that is not diagonally positioned in respect to the main menu. It's because "moving" the cursor diagonally can cause driver to "lose" the focus of the menu and which will make menu to fold. """ if "menu" in SECTIONS[group.lower()]: # Open the menu by sending "Enter" key menu_selector = SECTIONS[group.lower()]["menu"] menu = driver.find_element_by_css_selector(menu_selector) menu.send_keys(Keys.ENTER) menu_item_selector = SECTIONS[group.lower()][element.lower()] menu_item = find_element(driver, by_css=menu_item_selector) wait_for_visibility(driver, by_css=menu_item_selector) with assertion_msg("%s menu item: '%s' is not visible", group, element): assert menu_item.is_displayed() menu_item.click() take_screenshot( driver, NAME + " after clicking on: {} link".format(element))
def test_find_write_with_non_defaults(driver, element): """ Verify the waiter can find and write to an element, using non-default kwargs """ mock_id_path = "mock id" mock_write_string = "mock write string" driver.find_element.side_effect = [None, element] elem = waiter.find_write(driver, mock_id_path, mock_write_string, by=ID, clear_first=False, send_enter=True) # Element locating asserts assert driver.find_element.called assert elem is element assert len(driver.mock_calls) == 2 assert driver.find_element.call_args_list == [mock.call(ID, mock_id_path), mock.call(ID, mock_id_path)] # Element writing asserts assert not elem.clear.called assert len(elem.send_keys.call_args_list) == 2 assert elem.send_keys.call_args_list == [mock.call(mock_write_string), mock.call(Keys.ENTER)]
def login(self): if not self.quiet: print('[*] Logging in as {}'.format(self.account.document)) try: self.session.get(self.login_url) elem = self.wait.until(EC.visibility_of_element_located((By.ID, 'cpf'))) elem.send_keys(self.account.document) elem.send_keys(Keys.ENTER) elem = self.wait.until(EC.visibility_of_element_located((By.ID, 'password'))) elem.send_keys(self.account.password) for b in self.session.find_elements_by_class_name('botao'): if b.get_attribute('data-bind'): if 'userAuthentication' in b.get_attribute('data-bind'): b.click() break except Exception: traceback.print_exc() exit(1)
def test_donor_fills_wrong_info_and_gets_list_of_fields_to_correct(self): """ I will start testing only payment info and them try to make it more generic """ # Donor has heard about the opportunity to donate to the organization and enters the website self.browser.get(self.live_server_url) self.fill_in_donation_fields_right() self.fill_in_personal_fields_right() self.fill_in_cc_fields("411111111111111") # Missing one number # Submit submit = self.browser.find_element_by_name("subbtn") submit.send_keys(Keys.ENTER) self.wait_for(lambda: self.assertIn('Alguns dados precisam ser corrigidos:', self.browser.page_source)) self.assertIn('Erro nas informações de cartão de crédito enviadas.', self.browser.page_source)
def get_search_page(search_text): url = "http://www.gsxt.gov.cn/index.html" # driver = webdriver.Chrome("/home/hee/driver/chromedriver") driver = webdriver.Chrome("E:\\virtualenv\\chromedriver.exe") driver.get(url) wait = WebDriverWait(driver, 20) element = wait.until(EC.presence_of_element_located((By.ID, "keyword"))) element.clear() element.send_keys(search_text) # element.send_keys(Keys.ENTER) time.sleep(random.uniform(1.0,2.0)) element = driver.find_element_by_id("btn_query") element.click() wait = WebDriverWait(driver, 30) element = wait.until( EC.presence_of_element_located((By.CLASS_NAME, "gt_box"))) time.sleep(random.uniform(2.0, 3.0)) return driver
def _map_ascii_key_code_to_key(self, key_code): map = { 0: Keys.NULL, 8: Keys.BACK_SPACE, 9: Keys.TAB, 10: Keys.RETURN, 13: Keys.ENTER, 24: Keys.CANCEL, 27: Keys.ESCAPE, 32: Keys.SPACE, 42: Keys.MULTIPLY, 43: Keys.ADD, 44: Keys.SEPARATOR, 45: Keys.SUBTRACT, 56: Keys.DECIMAL, 57: Keys.DIVIDE, 59: Keys.SEMICOLON, 61: Keys.EQUALS, 127: Keys.DELETE } key = map.get(key_code) if key is None: key = chr(key_code) return key
def flush(browser, n): ua = DesiredCapabilities().IPHONE for i in range(n): if browser.lower() == 'firefox': driver = webdriver.Firefox() elif browser.lower() == 'chrome': options = webdriver.ChromeOptions() options.add_argument('--disable-extensions') driver = webdriver.Chrome(executable_path=driver_path + 'chromedriver.exe', chrome_options=options) elif browser.lower() == 'ie': driver = webdriver.Ie(executable_path=driver_path + 'IEDriverServer.exe') elif browser.lower() == 'phantomjs': killphantomjs() driver = webdriver.PhantomJS(executable_path=driver_path + 'phantomjs.exe', desired_capabilities=ua) driver.get('http://m.baidu.com') driver.find_element_by_id('index-kw').send_keys(random.choice(KEYWORDS), Keys.ENTER) clk(driver, url='csdn') sleep(1) print driver.find_element_by_class_name('article_t').text, print driver.find_element_by_xpath('//p[@class="date"]/i[2]').text driver.close()
def Transfer_Clicks(browser): try: browser.execute_script("window.scrollBy(0,document.body.scrollHeight)", "") # ???????Javascript?????????????? # browser.execute_script("window.scrollBy(0,5)", "") # ????200????????????? # ActionChains(browser).move_by_offset(0,-80).perform() # ??????80?????????? # ActionChains(browser).click().perform() # ?????? # ActionChains(browser).key_down(Keys.TAB).perform() # ??tab???? # ActionChains(browser).send_keys(Keys.ENTER).perform() # ????ENTER? except: pass return "Transfer successfully \n"
def make_user_and_login(self): # ??? ?? test_username = 'test_user' test_password = 'test_password' user = MyUser.objects.create_user(test_username, test_password) # ??? ??? ?? self.browser.get(self.make_url('/member/login/')) input_username = self.browser.find_element_by_id('id_username') input_username.send_keys(test_username) input_password = self.browser.find_element_by_id('id_password') input_password.send_keys(test_password) input_password.send_keys(Keys.ENTER) return user
def enter(self, message = None): self.log("Select active element") element = self.driver.switch_to.active_element element.send_keys(Keys.ENTER)
def enterAndSelectFromDropdown(self, by, value, text, message = None, nth = 1, \ dropdownBy = None, dropdownValue = None): element = self.assertElementPresent(by, value, message = message) if not element: self.onFail(by, value, message, "Not found") element = self.sendKeys(by, value, text) if dropdownBy: self.assertElementPresent(dropdownBy, dropdownValue, message) description = "{0}-th from {1} dropdown".format(nth, self.describeElement(by, value)) self.log("Find " + description) for i in range(1, nth+1): element = self.sendKeys(by, value, Keys.ARROW_DOWN) element = self.sendKeys(by, value, Keys.ENTER, message = "Select " + description) return element
def newMessageToFriend( self, friendname, message, image1=None, image2=None, image3=None): """Send message(str) to friend name (str), images doesn work in phantomjs""" url = "https://mbasic.facebook.com/friends/selector/?return_uri=%2Fmessages%2Fcompose%2F&cancel_uri=https%3A%2F%2Fm.facebook.com%2Fmessages%2F&friends_key=ids&context=select_friend_timeline&refid=11" self.get(url) q = self.find_element_by_name("query") q.send_keys(friendname) q.send_keys(Keys.ENTER) id = self.page_source.split( "/messages/compose/?ids=")[1].split('"><span>')[0].split('"><span>')[0] url = "https://mbasic.facebook.com/messages/compose/?ids=" + id self.get(url) t = self.find_element_by_name("body") t.send_keys(message) t.send_keys(Keys.ENTER) f1 = self.find_element_by_name("file1") f2 = self.find_element_by_name("file2") f3 = self.find_element_by_name("file3") if image1 is not None: f1.send_keys(image1) if image2 is not None: f2.send_keys(image2) if image3 is not None: f3.send_keys(image3) send = self.find_element_by_name("Send") send.send_keys(Keys.ENTER) return True
def postInGroup(self, groupURL, text): """Post text(str) in a group""" self.get(groupURL) try: tf = self.find_element_by_name("xc_message") except NoSuchElementException: print(" Group url doesn't exist or you don't have permissions to see it") return False tf.send_keys(text) self.find_element_by_name("view_post").send_keys(Keys.ENTER) return True
def commentInPost(self, postUrl, text): """Comment a text(str) in a post(str)""" try: self.get(postUrl) tb = self.find_element_by_name("comment_text") tb.send_keys(text) tb.send_keys(Keys.ENTER) return self.getScrenshotName( "CommentingIn_" + self.title, screenshot, screenshotPath) except Exception as e: print("Can't comment in ", postUrl, "\n->", e)
def send_message(self, msg): assert msg, "Message must be provided" input_message_field = WebDriverWait(self.driver, self.get_request_timeout_in_sec()).until( EC.presence_of_element_located(self.INPUT_MESSAGE_FIELD)) input_message_field.clear() self.random_sleep_send_keys(input_message_field, msg + Keys.ENTER) self.random_sleep_between_requests()
def test_switch_program(self, browser, base_test_data, logged_in_staff): """ Switching programs should show a different set of users """ existing_program_user_count = settings.ELASTICSEARCH_DEFAULT_PAGE_SIZE create_enrolled_user_batch(existing_program_user_count, program=base_test_data.program, is_staff=False) new_program = ProgramFactory.create(live=True) new_program_user_count = settings.ELASTICSEARCH_DEFAULT_PAGE_SIZE - 1 create_enrolled_user_batch(new_program_user_count, program=new_program, is_staff=False) ProgramEnrollment.objects.create(program=new_program, user=logged_in_staff) Role.objects.create( role=Staff.ROLE_ID, user=logged_in_staff, program=new_program, ) # Load the learners page for the existing program browser.get("/learners") browser.wait_until_element_count(By.CLASS_NAME, 'learner-result', existing_program_user_count) # Switch programs and check that the correct number of users are returned switcher = browser.driver.find_element_by_css_selector('.micromasters-header .Select-input') switcher.send_keys(Keys.DOWN) switcher.send_keys(Keys.ENTER) browser.wait_until_element_count(By.CLASS_NAME, 'learner-result', new_program_user_count) # Refresh browser and verify the count is the same browser.get("/learners") browser.wait_until_element_count(By.CLASS_NAME, 'learner-result', new_program_user_count)
def test_submit_form_with_enter_key(self): self.test_name = 'test_submit_form_with_enter_key' page = self.given_connect_page() self.when_correct_details(page) page.port.send_keys(Keys.ENTER) self.then_login_succeeds() self.then_no_js_error()
def login(driver, username, password): time.sleep(5) usernameElem = driver.find_element_by_id('identifierId') usernameElem.send_keys(username) usernameElem.send_keys(Keys.ENTER) time.sleep(3) passwordElem = driver.find_element_by_name('password') passwordElem.send_keys(password) passwordElem.send_keys(Keys.ENTER)
def keypair(self,cloud_controller_name): Cloud_DebugLog.stepinfo(Messages.LOGIN_CLOUD) #"Login cloud" Cloud_client_browser = self.driver # :???????? Login and pass in with username, password, server and port self.admin_cloud_login(username='admin') time.sleep(TestSpeedControl.TEST_STEP_INTERVAL) Cloud_DebugLog.stepinfo(Messages.CLICK_SET) Cloud_DebugLog.debug_print(Messages.CLICK_SET) Cloud_browser_main_map = Main_Browser_UIMap(Cloud_client_browser) openstatus=Cloud_client_browser.find_element_by_xpath("//span[text()='??']/../..").get_attribute("class") if openstatus=='open': pass else: safe_menu_btn=Cloud_browser_main_map.get_menu('security/') safe_menu_btn.click() safe_map=Safe_UIMap(Cloud_client_browser) safe_map.getelement("//span[text()='???']").click() time.sleep(1) safe_map.getelement("//*[@id='create_keypair']").click() time.sleep(1) keypairname='gyp'+"".join(random.sample('1234567890zyxwvutsrqponmlkjihgfedcba',5)) safe_map.getelement("//*[@id='modal_style']/div/div[2]/div/div/div[1]/input").send_keys(keypairname) safe_map.get_select(cloud_controller_name,name='cloud_controller_id') safe_map.getelement(id='id_button_submit').click() time.sleep(5) #safe_map.getelement("//*[@id='product-page']/div/h3").send_keys(Keys.ENTER) h3=safe_map.getelement("//*[@id='product-page']/div/h3").text a="???\""+keypairname+"\"??????????????????" assert h3==a
def _execute_script(email, password, count): print("\nLoading..\nCheck out today's xkcd comic till then : %s \n\n" %(_xkcd())) driver = webdriver.PhantomJS() driver.get('https://www.facebook.com') email_ID = driver.find_element_by_id('email') pass_ID = driver.find_element_by_id('pass') email_ID.send_keys(email) pass_ID.send_keys(password) pass_ID.send_keys(Keys.ENTER) sleep(5) for i in range(0,count): driver.execute_script("window.scrollBy(0, document.body.scrollHeight);") sleep(1) sleep(5) driver_tags = driver.execute_script('return document.getElementsByClassName("scaledImageFitWidth img")') driver_img_list = { 'src' : [x.get_attribute('src') for x in driver_tags], 'alt' : [x.get_attribute('alt') for x in driver_tags], } driver.quit() return driver_img_list
def test_castalio(self): driver = self.driver driver.get("http://castalio.info/") driver.find_element_by_id("tipue_search_input").send_keys("6 anos") driver.find_element_by_id("tipue_search_input").send_keys(Keys.ENTER) driver.find_element_by_link_text(u"Episódio 88: Episódio Especial de 6 Anos").click() self.assertEqual(u"Episódio 88: Episódio Especial de 6 Anos - Castálio Podcast", driver.title)
def test_cannot_add_empty_list_items(self): # Edith goes to the home page and accidentally tries to submit # an empty list item. She hits Enter on the empty input box self.browser.get(self.live_server_url) self.get_item_input_box().send_keys(Keys.ENTER) # The browser intercepts the request, and does not load the # list page self.wait_for(lambda: self.browser.find_elements_by_css_selector('#id_text:invalid')) # She starts typing some text for the new item and the error disappears self.get_item_input_box().send_keys('Buy milk') self.wait_for(lambda: self.browser.find_elements_by_css_selector('#id_text:valid')) # And she can submit it successfully self.get_item_input_box().send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy milk') # Perversely, she now decides to submit a second blank list item self.get_item_input_box().send_keys(Keys.ENTER) # Again, the browser will not comply self.wait_for_row_in_list_table('1: Buy milk') self.wait_for(lambda: self.browser.find_elements_by_css_selector('#id_text:invalid')) # And she can correct it by filling some text in self.get_item_input_box().send_keys('Make tea') self.wait_for(lambda: self.browser.find_elements_by_css_selector('#id_text:valid')) self.get_item_input_box().send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy milk') self.wait_for_row_in_list_table('2: Make tea')
def test(name,chat): print ('ok here') #elem = weixin_main.driver.find_element_by_name("editor") #elem = weixin_main.driver.find_element_by_class_name("web_wechat_search") friend_name = weixin_main.driver.find_element_by_tag_name("input") #elem.click() friend_name.send_keys(name) time.sleep(3) friend_name.send_keys(Keys.ENTER) chat_content = weixin_main.driver.find_element_by_id("editArea") time.sleep(1) chat_content.send_keys(chat) #elem.send_keys(Keys.ENTER) print ('ok here1')
def test(name,chat): print ('hello011') #???? timedelta=datetime.timedelta(minutes=5) #????? now = str(datetime.datetime.now())[:-7] next=now #???????????,????????????? while True: print ('hello012') now = str(datetime.datetime.now())[:-7] if now==next: #print (sched_time) next=str(datetime.datetime.now()+timedelta)[:-7] #print (sched_time) print ('??????????') chat=???????.main() print ('abc is ',chat) #elem = weixin_main.driver.find_element_by_name("editor") #elem = weixin_main.driver.find_element_by_class_name("web_wechat_search") friend_name = weixin_main.driver.find_element_by_tag_name("input") #elem.click() friend_name.send_keys(name) time.sleep(3) friend_name.send_keys(Keys.ENTER) chat_content = weixin_main.driver.find_element_by_id("editArea") time.sleep(1) chat_content.send_keys(chat) time.sleep(2) time.sleep(1) #chat_content.send_keys(Keys.ENTER) #elem.send_keys(Keys.ENTER) print ('ok here1') print ('ok here')
def search(self, phrase): """ Enter a search phrase and display the results """ selector = 'input.gsc-input' self.wait_for_element_visibility(selector, 'Search input available') self.q(css=selector).fill(phrase + Keys.ENTER) self.wait_for_element_visibility('.gsc-results', 'Search results shown')
def should_see_link_to(driver: webdriver, section: str, item_name: str): item_selector = SECTIONS[section.lower()][item_name.lower()] if section.lower() in ["export readiness", "guidance", "services"]: logging.debug("Open the menu by sending 'Right Arrow' key") menu_selector = SECTIONS[section.lower()]["menu"] menu = find_element(driver, by_css=menu_selector) menu.send_keys(Keys.ENTER) menu_item = find_element(driver, by_css=item_selector) wait_for_visibility(driver, by_css=item_selector) with assertion_msg( "It looks like '%s' in '%s' section is not visible", item_name, section): assert menu_item.is_displayed()
def start_requests(self): def _search(driver): driver.find_element_by_id('key').send_keys(u"?????", Keys.ENTER) gevent.sleep(3) self._jump_guide(driver) gevent.sleep(3) yield Request(url='https://www.jd.com/', meta={"cookiejar": "jd"}, callback=self.parse_list, dynamic=True, browser_actions=[_search] )
def find_write(driver, elem_path, write_str, clear_first=True, send_enter=False, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string to it. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element write_str (str): String to write clear_first (bool): Clear the contents before writing (default True) send_enter (bool): Send a keyboard ENTER after writing string by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located """ elem = find_element(driver, elem_path=elem_path, by=by, timeout=timeout, poll_frequency=poll_frequency) if clear_first: elem.clear() elem.send_keys(write_str) if send_enter: elem.send_keys(Keys.ENTER) return elem
def test_can_enter_donation_form_and_execute_donation(self): # Donor has heard about the opportunity to donate to the organization and enters the website self.browser.get(self.live_server_url) self.fill_in_donation_fields_right() self.fill_in_personal_fields_right() self.fill_in_cc_fields("4111111111111111") # Submit submit = self.browser.find_element_by_name("subbtn") submit.send_keys(Keys.ENTER) self.wait_for(lambda: self.assertIn('Muito obrigado pela sua doação!', self.browser.page_source))
def test_donor_fills_wrong_credit_card_and_gets_error(self): # Donor has heard about the opportunity to donate to the organization and enters the website self.browser.get(self.live_server_url) self.fill_in_donation_fields_right() self.fill_in_personal_fields_right() self.fill_in_cc_fields("4111111111111112") # Submit submit = self.browser.find_element_by_name("subbtn") submit.send_keys(Keys.ENTER) self.wait_for(lambda: self.assertIn('Erro nas informações de cartão de crédito enviadas.', self.browser.page_source))
def __init__(self): '''change these variables to fit your needs''' '''Go to twilio.com and create a free account''' self.accountsid = '??????????' # accountsid for twilio account, required to receive texts self.authtoken = '??????????' # authtoken for twilio account, required to receive texts self.mycellphone = '??????????' # your cell phone number self.twiliocell = '??????????' # twilio cellnumber that will be used to send texts to your actual phone self.username = '??????????' # CUNYFIRST USERNAME self.password = '??????????' # CUNYFIRST PASSWORD '''In order to receive an email you must go myaccount.google.com/security and scroll all the way to he bottom. Then go to where it says 'Allow less secure apps: ON' and check OFF. You should get an email about the change ''' self.gmailuser = '??????????' # GMAIL USER self.gmailpass = '??????????' # GMAIL PASSWORD self.recipient = '??????????' # Recipient email address (most likely your email) self.interval = 60 # refresh interval in seconds '''Add shopping cart link is very important to this script. Go to CUNYFIRST, Click Enroll. Then choose your Term. Once you are are on the Shopping Cart Page, Right + Click on 'add' and Click on 'Copy Link Location'. Then copy and paste in here with single quotes. It should look like the link below''' self.addshoppingcartlink = 'https://hrsa.cunyfirst.cuny.edu/psc/cnyhcprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_CART.GBL?Page=SSR_SSENRL_CART&Action=A&ACAD_CAREER=UGRD&EMPLID=12345678&ENRL_REQUEST_ID=&INSTITUTION=BKL01&STRM=1172' print("Starting Firefox and heading to CUNYFIRST") self.driver = webdriver.PhantomJS() self.driver.get('https://home.cunyfirst.cuny.edu') login = WebDriverWait(self.driver, timeout=30).until( EC.presence_of_element_located((By.NAME, "login"))) login.send_keys(self.username) passs = self.driver.find_element_by_name("password") passs.send_keys(self.password, Keys.ENTER) studentcenter = WebDriverWait(self.driver, timeout=30).until( EC.presence_of_element_located((By.LINK_TEXT, "Student Center"))) studentcenter.click() self.driver.get(self.addshoppingcartlink) shoppingcartlen = len(self.driver.find_elements_by_xpath("//table[@id='SSR_REGFORM_VW$scroll$0']/tbody/tr")) - 2 self.shoppingcart = {} for i in range(0, shoppingcartlen): classname = self.driver.find_element_by_id("win0divP_CLASS_NAME$" + str(i)).text print(classname) status = self.driver.find_element_by_xpath( "//div[@id='win0divDERIVED_REGFRM1_SSR_STATUS_LONG$" + str(i) + "']/div/img").get_attribute('alt') self.shoppingcart[classname] = status
def login_to_lichess(username, password): # login to Lichess chrome.get('https://en.lichess.org/login') login = chrome.find_element_by_id('username') login.send_keys(username) passwordField = chrome.find_element_by_id('password') passwordField.send_keys(password) passwordField.send_keys(Keys.ENTER)
def auth(self,uname,passd): time.sleep(2) username = self.driver.find_element_by_id('email') password = self.driver.find_element_by_id('pass') username.send_keys(uname) password.send_keys(passd) password.send_keys(Keys.ENTER)
def _slow_type(self,word,elem): """ Mimics a human user typing """ typing_speed = 42 #50 #wpm for letter in word: elem.send_keys(letter) time.sleep(random.random()*10.0/typing_speed) elem.send_keys(Keys.ENTER)