我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用selenium.webdriver.common.by.By.NAME。
def setUp(self): self.driver = self.getDriver() print("Got driver") self.driver.get(os.environ["OS_HORIZON"]) try: delay = 5 element_present = EC.presence_of_element_located((By.NAME, 'username')) WebDriverWait(self.driver, delay).until(element_present) self.driver.title.index("Login - OpenStack Dashboard") elem = self.driver.find_element_by_name("username") elem.send_keys(os.environ["OS_USERNAME"]) elem = self.driver.find_element_by_name("password") elem.send_keys(os.environ["OS_PASSWORD"]) elem.send_keys(Keys.RETURN) except TimeoutException: print("Loading took too much time!") raise time.sleep(2)
def solve_captcha(url, api, driver, timestamp): driver.get(url) WebDriverWait(driver, 86400).until(EC.text_to_be_present_in_element_value((By.NAME, "g-recaptcha-response"), "")) driver.switch_to.frame(driver.find_element_by_xpath("//*/iframe[@title='recaptcha challenge']")) token = driver.find_element_by_id("recaptcha-token").get_attribute("value") request = api.create_request() request.verify_challenge(token=token) request.get_hatched_eggs() request.get_inventory(last_timestamp_ms=timestamp) request.check_awarded_badges() request.get_buddy_walked() request.check_challenge() for attempt in range(-1, conf.MAX_RETRIES): try: responses = await request.call() return responses['VERIFY_CHALLENGE'].success except (ex.HashServerException, ex.MalformedResponseException, ex.ServerBusyOrOfflineException) as e: if attempt == conf.MAX_RETRIES - 1: raise else: print('{}, trying again soon.'.format(e)) await sleep(4) except (KeyError, TypeError): return False
def frame(self, frame_reference): """ Switches focus to the specified frame, by index, name, or webelement. :Args: - frame_reference: The name of the window to switch to, an integer representing the index, or a webelement that is an (i)frame to switch to. :Usage: driver.switch_to.frame('frame_name') driver.switch_to.frame(1) driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0]) """ if isinstance(frame_reference, basestring) and self._driver.w3c: try: frame_reference = self._driver.find_element(By.ID, frame_reference) except NoSuchElementException: try: frame_reference = self._driver.find_element(By.NAME, frame_reference) except NoSuchElementException: raise NoSuchFrameException(frame_reference) self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
def try_login(self, until=1): """Fill in the login form and submit. If the login panel is not found, chack that we are already logged in.""" if self.exists('#login', until): self.wait(EC.presence_of_element_located((By.NAME, 'username')), 2) username_input = self.driver.find_element_by_name('username') password_input = self.driver.find_element_by_name('password') submit_button = self.driver.find_element_by_class_name('submit-button') username_input.clear() password_input.clear() username_input.send_keys('test') password_input.send_keys('test') submit_button.click() return 1 else: return 0
def find_element(self, by=By.ID, value=None): if not By.is_valid(by) or not isinstance(value, str): raise InvalidSelectorException("Invalid locator values passed in") if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value']
def find_elements(self, by=By.ID, value=None): if not By.is_valid(by) or not isinstance(value, str): raise InvalidSelectorException("Invalid locator values passed in") if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})['value']
def find_element(self, by=By.ID, value=None): """ 'Private' method used by the find_element_by_* methods. :Usage: Use the corresponding find_element_by_* instead of this. :rtype: WebElement """ if not By.is_valid(by) or not isinstance(value, str): raise InvalidSelectorException("Invalid locator values passed in") if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, {'using': by, 'value': value})['value']
def find_element(self, by=By.ID, value=None): if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value']
def find_elements(self, by=By.ID, value=None): if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})['value']
def find_element(self, by=By.ID, value=None): """ 'Private' method used by the find_element_by_* methods. :Usage: Use the corresponding find_element_by_* instead of this. :rtype: WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value']
def find_elements(self, by=By.ID, value=None): """ 'Private' method used by the find_elements_by_* methods. :Usage: Use the corresponding find_elements_by_* instead of this. :rtype: list of WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENTS, { 'using': by, 'value': value})['value']
def logIn(self): self.user = User.objects.create_user(self.profile['username'], self.profile['mail'], self.profile['password']) site_permission = SitePermission.objects.create(user=self.user) site_permission.sites.set(Site.objects.filter(id=1)) site_permission.save() self.driver.get('%s%s' % (self.live_server_url, '/login/')) username_input = self.find(By.NAME, 'username') self.clear(username_input) username_input.send_keys(self.profile['username']) password_input = self.find(By.NAME, 'password') self.clear(password_input) password_input.send_keys(self.profile['password']) self.find(By.NAME, 'login').click() self.waitForPresence((By.ID, 'nav-app'))
def test_projects_add(self): Client(name='Client', archive=False).save() self.logIn() self.addPerms(['view_client', 'view_project']) self.driver.get('%s%s' % (self.live_server_url, '/clients/')) self.assertNotIn('project-add', self.driver.page_source) self.addPerms(['add_project']) self.driver.refresh() self.find(By.NAME, 'project-add').click() self.waitForPresence((By.ID, 'project-modal')) self.select2Select('project-client', 'Client') self.find(By.NAME, 'project-name').send_keys('Project') self.find(By.NAME, 'project-estimate').send_keys('100.00') self.find(By.NAME, 'project-modal-submit').click() self.waitForPresence((By.CLASS_NAME, 'project'))
def test_tasks_change(self): Task(name='Task', hourly_rate=25).save() self.logIn() self.addPerms(['view_task']) self.driver.get('%s%s' % (self.live_server_url, '/tasks/')) self.assertNotIn('task-menu-change', self.driver.page_source) self.addPerms(['change_task']) self.driver.refresh() self.find(By.NAME, 'task-menu').click() self.find(By.ID, 'task-menu-change').click() self.waitForPresence((By.NAME, 'task-name')) self.find(By.NAME, 'task-name').send_keys(' Changed') hourly_rate_field = self.find(By.NAME, 'task-hourly-rate') hourly_rate_field.click() self.clear(hourly_rate_field) hourly_rate_field.send_keys('125') self.find(By.NAME, 'task-modal-submit').click() self.waitForText((By.CLASS_NAME, 'task'), 'Task Changed\n$125')
def test_timesheet_entry_delete(self): client = Client(name='Client', archive=False) client.save() project = Project(name='Project 1', estimate=100.00, client=client, archive=False) project.save() task = Task(name='Task 1', hourly_rate=130) task.save() # Log in to establish self.user. self.logIn() Entry(project=project, task=task, user=self.user, note='Note', duration=timedelta(minutes=35)).save() self.addPerms(['view_entry', 'delete_entry']) self.driver.get('%s%s' % (self.live_server_url, '/timesheet/')) self.waitForPresence((By.NAME, 'entry-menu')) self.find(By.NAME, 'entry-menu').click() self.waitForPresence((By.CLASS_NAME, 'entry-menu-delete')) self.find(By.CLASS_NAME, 'entry-menu-delete').click() self.assertNotIn('entry', self.find(By.ID, 'entry-rows').text)
def authenticate(self): self.driver.get(ENTRY_URL) try: user = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.NAME, 'loginfmt')) ) except (NoSuchElementException, TimeoutException) as err: print("Couldn't initialize browser: %s", err) else: pass_ = self.driver.find_element_by_name("passwd") user.send_keys(self.user) pass_.send_keys(self.pw) user.submit() time.sleep(5) self.authToken = self.driver.get_cookie('MSPAuth')
def raven_login(cls, crsid=None, password=None, fill_details=True): if crsid == None: crsid = "test0%03d" % ( randint(0, 400) ) password = "test" # First ensure we are logged out cls.logout() # Now login cls.browser.get("http://localhost:%i/" % cls.port_num) # Click the raven link link = cls.browser.find_element(By.ID, "ravenbutton") link.click() sleep(1) # We should now be at the Raven testing login page assert "Demonstration Authentication Service" in cls.browser.page_source assert Raven.our_description in cls.browser.page_source # Fill in the login details user = cls.browser.find_element(By.ID, "userid") user.send_keys(crsid) pwd = cls.browser.find_element(By.ID, "pwd") pwd.send_keys(password) cls.browser.find_element(By.NAME, "credentials").submit() # Fill details automatically fills the profile if fill_details: filled_state = { "fullname": "Automated Test User", "dob_day": "15", "dob_month": "3", "dob_year": "1987", "photofile": cls.root_path() + "/data/profile_images/dummy.png", "college": "sidney-sussex", "grad_status": "undergrad", } # Now run a full valid fill and check for no validation fault cls.browser.get(cls.route_path("user_profile_edit")) for key in filled_state: cls.browser.find_element(By.ID, key).send_keys(filled_state[key]) # Submit cls.browser.find_element(By.ID, "submit").click() # Return credentials used return (crsid, password)
def find_element_by_name(self, name): """Finds element within this element's children by name. :Args: - name - name property of the element to find. """ return self.find_element(by=By.NAME, value=name)
def find_elements_by_name(self, name): """Finds a list of elements within this element's children by name. :Args: - name - name property to search for. """ return self.find_elements(by=By.NAME, value=name)
def find_element_by_name(self, name): """ Finds an element by name. :Args: - name: The name of the element to find. :Usage: driver.find_element_by_name('foo') """ return self.find_element(by=By.NAME, value=name)
def find_elements(self, by=By.ID, value=None): """ 'Private' method used by the find_elements_by_* methods. :Usage: Use the corresponding find_elements_by_* instead of this. :rtype: list of WebElement """ if not By.is_valid(by) or not isinstance(value, str): raise InvalidSelectorException("Invalid locator values passed in") if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENTS, {'using': by, 'value': value})['value']
def find_element_by_name(self, name): return self.find_element(by=By.NAME, value=name)
def find_elements_by_name(self, name): return self.find_elements(by=By.NAME, value=name)
def find_elements_by_name(self, name): """ Finds elements by name. :Args: - name: The name of the elements to find. :Usage: driver.find_elements_by_name('foo') """ return self.find_elements(by=By.NAME, value=name)
def get_token(self, url): token = '' path = os.getcwd() if _platform == "Windows" or _platform == "win32": # Check if we are on 32 or 64 bit file_name= 'chromedriver.exe' if _platform.lower() == "darwin": file_name= 'chromedriver' if _platform.lower() == "linux" or _platform.lower() == "linux2": file_name = 'chromedriver' full_path = '' if os.path.isfile(path + '/' + file_name): # check local dir first full_path = path + '/' + file_name if full_path == '': self.bot.logger.error(file_name + ' is needed for manual captcha solving! Please place it in the bots root directory') sys.exit(1) try: driver = webdriver.Chrome(full_path) driver.set_window_size(600, 600) except Exception: self.bot.logger.error('Error with Chromedriver, please ensure it is the latest version.') sys.exit(1) driver.get(url) elem = driver.find_element_by_class_name("g-recaptcha") driver.execute_script("arguments[0].scrollIntoView(true);", elem) self.bot.logger.info('You have 1 min to solve the Captcha') try: WebDriverWait(driver, 60).until(EC.text_to_be_present_in_element_value((By.NAME, "g-recaptcha-response"), "")) token = driver.execute_script("return grecaptcha.getResponse()") driver.close() except TimeoutException, err: self.bot.logger.error('Timed out while trying to solve captcha') driver.quit() return token
def host(self): return self.wait_locate_visible_element((By.NAME, 'address'))
def port(self): return self.wait_locate_visible_element((By.NAME, 'port'))
def data_search(self,content): self.find_ele(By.NAME,"mixedCondition2").send_keys(content) sleep(1)
def data_search_click(self): self.find_ele(By.NAME,"mixedCondition2").send_keys(Keys.ENTER) sleep(1) # ??table tr ??
def check_all(self): self.find_ele(By.NAME,"teamAllId").click() sleep(1) # ??????????