我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用selenium.webdriver.common.by.By.CLASS_NAME。
def populate_text_field(driver, element_locator, text): '''Populates text field with provided text Args: element_locator ((selenium.webdriver.common.by.By., str)): element locator described using `By`. Take a look at `Locate elements By <http://selenium-python.readthedocs.io/api.html#locate-elements-by>`_ for more info. text (str): text to populate text field with. Example: :: from selenium import webdriver from selenium.webdriver.common.by import By from selenium_extensions.core import populate_text_field driver = webdriver.Chrome() ... populate_text_field(driver, (By.CLASS_NAME, 'textbox'), 'some text') ''' input_element = driver.find_element(*element_locator) input_element.send_keys(text)
def get_position(self): """ ??????? :return: ??????? """ try: img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'patt-shadow'))) except TimeoutException: print('??????') self.open() time.sleep(2) location = img.location size = img.size top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size[ 'width'] return (top, bottom, left, right)
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 shot_pages(live_server, organizer, event, logged_in_client, page_faq, page_tos): event.plugins += ',pretix_pages' event.save() logged_in_client.get(live_server.url + '/control/event/{}/{}/pages'.format( organizer.slug, event.slug )) screenshot(logged_in_client, 'plugins/pages/list.png') logged_in_client.get(live_server.url + '/control/event/{}/{}/pages/{}/'.format( organizer.slug, event.slug, page_tos.pk )) WebDriverWait(logged_in_client, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "ql-formats")) ) time.sleep(.5) screenshot(logged_in_client, 'plugins/pages/edit.png') logged_in_client.get(live_server.url + '/{}/{}/page/{}/'.format( organizer.slug, event.slug, page_faq.slug )) screenshot(logged_in_client, 'plugins/pages/frontend.png')
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 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 repeat_next(self): while True: try: next_button = self.wait.until( EC.element_to_be_clickable( (By.CLASS_NAME, 'float-right')) ) pages = self.driver.find_elements(By.CSS_SELECTOR, '.current.reference.internal') for page in pages: ("\n" + page.get_attribute('text')) self.click(next_button) except NoSuchElementException: print("End of page") break except TimeoutException: print("Timeout error...") break
def open_user_menu(self): """ Hamburger (user) menu opener. ToDo: branching to handle if a toggle is already open """ """if self.get_window_size('width') <= self.CONDENSED_WIDTH: # compressed window display on Tutor self.wait.until( expect.visibility_of_element_located( (By.CLASS_NAME, 'navbar-toggle') ) ).click()""" self.wait.until( expect.visibility_of_element_located( (By.CSS_SELECTOR, '#user-actions-menu') ) ).click()
def goto_performance_forecast(self): """Access the performance forecast page.""" print('Enter: goto_performance_forecast') self.goto_menu_item('Performance Forecast') timer = 0 while timer < 10: try: print('Wait for forecast load try %s of 10' % (timer + 1)) self.wait.until( expect.visibility_of_element_located( (By.CLASS_NAME, 'guide-container') ) ) timer = 10 except: timer = timer + 1 print('Exit: goto_performance_forecast')
def get_enrollment_code(self, section_name): """Return the enrollment code for a class section.""" print('Enter: get_enrollment_code') if 'settings' not in self.driver.current_url: self.goto_course_roster() self.find(By.XPATH, '//a[text()="%s"]' % section_name).click() self.wait.until( expect.element_to_be_clickable( (By.CLASS_NAME, 'show-enrollment-code') ) ).click() sleep(1) code = self.wait.until( expect.presence_of_element_located( (By.CLASS_NAME, 'code') ) ) print('Exit: get_enrollment_code') return '%s' % code.text.strip()
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_projects_change(self): client = Client(name='Client', archive=False) client.save() Project(name='Project', client=client, estimate=100.00, archive=False).save() self.logIn() self.addPerms(['view_client', 'view_project']) self.driver.get('%s%s' % (self.live_server_url, '/clients/')) self.assertNotIn('project-menu', self.driver.page_source) self.addPerms(['change_project']) self.driver.refresh() self.waitForClickable((By.NAME, 'project-menu')) self.find(By.NAME, 'project-menu').click() self.find(By.ID, 'project-menu-change').click() self.waitForPresence((By.NAME, 'project-name')) self.find(By.NAME, 'project-name').send_keys(' Changed') self.clear(self.find(By.NAME, 'project-estimate')) self.find(By.NAME, 'project-estimate').send_keys('50.00') self.find(By.NAME, 'project-modal-submit').click() self.waitForText((By.CLASS_NAME, 'project-name'), 'Project Changed')
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 find_class_with_timeout(driver, CLASS, timeout=TIMEOUT): return WebDriverWait(driver, timeout).until( EC.presence_of_element_located((By.CLASS_NAME, CLASS)) )
def login(email, senha, firefox): firefox.get('http://acervus.unicamp.br/asp/login.asp?modo_busca=rapida&content=mensagens&iBanner=0&iEscondeMenu=0&iSomenteLegislacao=0&iIdioma=0') firefox.implicitly_wait(10) WebDriverWait(firefox, 60).until(EC.visibility_of_element_located((By.ID, 'button1'))) try: input_login = firefox.find_element_by_name("codigo") input_login.send_keys(email) input_pwd = firefox.find_element_by_name("senha") input_pwd.send_keys(senha) send_button = firefox.find_element_by_id("button1") send_button.click() WebDriverWait(firefox, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, 'justificado'))) except Exception, err: error_message = "Erro no login. Verifique usuário e senha." print error_message logging.exception(error_message) raise return
def linkedinrec_people(url): """ Get's the 10 "People Also Viewed" from a person's url """ time.sleep(2) driver.get(url) driver.implicitly_wait(15) try: wait = WebDriverWait(driver, 15) wait.until(EC.presence_of_element_located((By.CLASS_NAME, "right-rail"))) wait.until(EC.presence_of_element_located((By.TAG_NAME, "ul"))) wait.until(EC.presence_of_element_located((By.TAG_NAME, "li"))) a = driver.find_element_by_class_name('right-rail') cr = driver.find_element_by_class_name('core-rail') yr = cr.find_element_by_tag_name('section') xr = yr.find_elements_by_tag_name('div') ar = xr[5].text.split('\n') sr = ar[0] + ' ' + ar[1] y = a.find_element_by_tag_name('ul') x = y.find_elements_by_tag_name('li') title = [x[i].text.replace('\n', ' ') for i in range(len(x))] title.append(sr) link = [i.find_element_by_tag_name('a').get_attribute('href') for i in x] link.append(url) profile_detail = driver.find_element_by_class_name('profile-detail') summary = profile_detail.find_elements_by_class_name('pv-entity__summary-info') # experience = [i.find_element_by_tag_name('h3').text for i in summary] # education = profile_detail.find_element_by_class_name('pv-entity__degree-info').text.split('\n') # accomplishment = profile_detail.find_element_by_class_name('pv-accomplishments-block__content') # print(accomplishment.text) # interest = profile_detail.find_element_by_class_name('pv-deferred-area__content') # int_li = interest.find_elements_by_tag_name('li') # for i in int_li: # print(i.text) # return list(zip(title, link)) except: print('Cannot find it..') driver.quit()
def get_person_header(self, url): """ Return the Person's Name + Header + Url """ self.driver.get(url) ret_list = [] try: wait = WebDriverWait(self.driver, 20) wait.until(EC.presence_of_element_located((By.CLASS_NAME, "pv-top-card-section__body"))) try: initial_div = self.driver.find_element_by_class_name('pv-top-card-section__body') main_div = initial_div.find_element_by_tag_name('div') name = main_div.find_element_by_tag_name('h1') ret_list.append(name.text) header = main_div.find_element_by_tag_name('h2') ret_list.append(header.text) ret_list.append(url) except: pass return ret_list except: raise Exception('Cannot find it..')
def get_people_viewed(self, url): """ Parses's the Person's Name + Header and also parse's the 10 "People Also Viewed" from a person's url Returns list of tuples with (Name + Header, url) If people also viewed option not available, list will just be len(1) (Rarely, Selenium doesn't pick up the JS DOM, so the script tries 2 more times before raising an exception) """ self.driver.get(url) # count = 0 try: wait = WebDriverWait(self.driver, 20) wait.until(EC.presence_of_element_located((By.CLASS_NAME, "right-rail"))) # wait.until(EC.presence_of_element_located((By.TAG_NAME, "ul"))) # wait.until(EC.presence_of_element_located((By.TAG_NAME, "li"))) a = self.driver.find_element_by_class_name('right-rail') cr = self.driver.find_element_by_class_name('core-rail') y = a.find_element_by_tag_name('ul') x = y.find_elements_by_tag_name('li') link = [i.find_element_by_tag_name('a').get_attribute('href') for i in x] link.append(url) return link except: raise Exception('Tried and Cannot find it..') # self.driver.quit()
def release_tickets(cls, type_name, quantity=100): # Login cls.admin_login() # Find the release link and click it cls.browser.get(cls.route_path("admin_tickets")) row = 1 found = False while cls.is_element_present("//table/tbody/tr[%i]/td[1]" % row): name = cls.browser.find_element_by_xpath("//table/tbody/tr[%i]/td[1]" % row).text if type_name in name: cell = cls.browser.find_element_by_xpath("//table/tbody/tr[%i]/td[4]" % row) cell.find_element(By.CLASS_NAME, "release_tick_link").click() found = True break row += 1 assert found, "Didn't find release link for ticket type!" # Now actually release some tickets cls.browser.find_element(By.ID, "number").send_keys(str(quantity)) cls.browser.find_element(By.ID, "submit").click() # Deal with modal alert try: cls.browser.switch_to_alert().accept() except Exception: pass # Catch for PhantomJS # Logout cls.logout() # Return quantity return quantity
def loadmap(self): ''' loadmap() Creates a browser object and loads the webpage. It sets up the map to the proper zoom level. Returns the browser on success, None on fail. ''' browser = webdriver.PhantomJS(desired_capabilities={'phantomjs.page.settings.resourceTimeout': '20000'}) browser.set_window_size(abovetustin_image_width, abovetustin_image_height) print("getting web page {}".format(self.url)) browser.set_page_load_timeout(15) browser.get(self.url) # Need to wait for the page to load timeout = g_request_timeout print ("waiting for page to load...") wait = WebDriverWait(browser, timeout) element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'vrsMenu'))) self.browser = browser
def find_element_by_class_name(self, name): """Finds element within this element's children by class name. :Args: - name - class name to search for. """ return self.find_element(by=By.CLASS_NAME, value=name)
def find_elements_by_class_name(self, name): """Finds a list of elements within this element's children by class name. :Args: - name - class name to search for. """ return self.find_elements(by=By.CLASS_NAME, value=name)
def find_element_by_class_name(self, name): """ Finds an element by class name. :Args: - name: The class name of the element to find. :Usage: driver.find_element_by_class_name('foo') """ return self.find_element(by=By.CLASS_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_class_name(self, name): return self.find_element(by=By.CLASS_NAME, value=name)
def find_elements_by_class_name(self, name): return self.find_elements(by=By.CLASS_NAME, value=name)
def get_geetest_button(self): """ ???????? :return: """ button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_radar_tip'))) return button
def get_position(self): """ ??????? :return: ??????? """ img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img'))) time.sleep(2) location = img.location size = img.size top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size[ 'width'] return (top, bottom, left, right)
def get_slider(self): """ ???? :return: ???? """ slider = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button'))) return slider
def login(self): """ ?? :return: None """ submit = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'login-btn'))) submit.click() time.sleep(10) print('????')
def crack(self): # ??????? self.open() # ?????? button = self.get_geetest_button() button.click() # ??????? image1 = self.get_geetest_image('captcha1.png') # ?????? slider = self.get_slider() slider.click() # ??????????? image2 = self.get_geetest_image('captcha2.png') # ?????? gap = self.get_gap(image1, image2) print('????', gap) # ?????? gap -= BORDER # ?????? track = self.get_track(gap) print('????', track) # ???? self.move_to_gap(slider, track) success = self.wait.until( EC.text_to_be_present_in_element((By.CLASS_NAME, 'geetest_success_radar_tip_content'), '????')) print(success) # ????? if not success: self.crack() else: self.login()
def test_zero_price_purchase(browser, base_test_data, logged_in_student, mocker): """ Test that a course can be purchased with a 100%-off coupon """ mocker.patch('ecommerce.views.enroll_user_on_success') # Make a 100% off coupon. By setting the price to $0 we can avoid dealing with Cybersource coupon = CouponFactory.create( amount=1, amount_type=Coupon.PERCENT_DISCOUNT, coupon_type=Coupon.STANDARD, content_object=base_test_data.program ) UserCoupon.objects.create(coupon=coupon, user=logged_in_student) browser.get("/") # Click the dashboard link on the upper right of the homepage browser.click_when_loaded(By.CLASS_NAME, "header-dashboard-link") browser.assert_no_console_errors() browser.click_when_loaded(By.CLASS_NAME, "enroll-button") browser.wait_until_loaded(By.CLASS_NAME, "continue-payment") # Click back then click the enroll now button again to assert back button behavior browser.driver.back() browser.click_when_loaded(By.CLASS_NAME, "enroll-button") browser.assert_no_console_errors() # Click 'Continue' on the order summary page browser.click_when_loaded(By.CLASS_NAME, "continue-payment") browser.assert_no_console_errors() browser.wait_until_loaded(By.CLASS_NAME, "toast-message") # Assert that the purchase went through fine but enrolling in edX failed # Which makes sense since there is no edX for these tests assert browser.driver.find_element_by_css_selector(".course-status-messages .status-message .message").text == ( "Something went wrong. You paid for this course but are not enrolled. Contact us for help." ) browser.assert_no_console_errors()