Exemplo n.º 1
0
	def test_add_booking (self):
		self.browser.get(self.live_server_url+"/bookings_sys/add_booking/")
		assert 'Add a New Booking' in self.browser.title
		#Type in the information properly.
		self.fill_in_box('surname','Palmer')
		self.fill_in_box('title','Mr')
		self.fill_in_box('initial','S J')
		self.fill_in_box('add1','66 Ambler Rd')
		self.fill_in_box('add2','')
		self.fill_in_box('town','London')
		self.fill_in_box('postcode','N4 2QR')
		self.fill_in_box('country','')
		self.fill_in_box('mobile','07947003829')
		self.fill_in_box('email','*****@*****.**')
		self.fill_in_box('telephone','020 7226 6599')
		select = Select(self.browser.find_element_by_id('id_house'))
		select.select_by_visible_text('Villa Magnifimundo')
		select = Select(self.browser.find_element_by_id('id_authorised_user'))
		select.select_by_visible_text('paul')
		#Hit save
		self.browser.find_element_by_id('id_submit').click()

		#Redirect to a results page.
		new_url = self.browser.current_url
		self.assertRegex(new_url, '/confirmation/.+')
		#self.fail("finish test add booking")
		assert 'Booking Added Successfully' in self.browser.title
 def search_for_class(self):
     self.driver.get(self.search_url)
     self.driver.switch_to.frame(self.driver.find_element_by_name('TargetContent'))
     
     select = Select(self.driver.find_element_by_id('CLASS_SRCH_WRK2_STRM$35$'))
     select.select_by_visible_text('2015 Spring')
     time.sleep(0.5)
     self.driver.find_element_by_id('SSR_CLSRCH_WRK_SUBJECT$0').send_keys(self.dept)
     time.sleep(0.5)
     self.driver.find_element_by_id('SSR_CLSRCH_WRK_SSR_OPEN_ONLY$3').click()
     time.sleep(0.5)
     self.driver.find_element_by_id('SSR_CLSRCH_WRK_CATALOG_NBR$1').send_keys(self.course_number)
     #really weird, but in phantomjs, the open class only button is deselected by default, uncomment next line if problems
     #self.driver.find_element_by_id('SSR_CLSRCH_WRK_SSR_OPEN_ONLY_LBL$3').click()
     self.driver.find_element_by_name('DERIVED_CLSRCH_SSR_EXPAND_COLLAPS$149$$IMG$1').click()
     self.driver.find_element_by_id('SSR_CLSRCH_WRK_CLASS_NBR$8').send_keys(self.class_number)
     self.driver.find_element_by_id('CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH').click()
     time.sleep(0.5)
     self.driver.save_screenshot('test.jpg')
     alt_text = self.driver.find_element_by_class_name('SSSIMAGECENTER').get_attribute('alt')
     if (alt_text == 'Open' or alt_text == 'Wait Listed'):
         robot = RegistryBot(self.username, self.password)
         robot.login()
         robot.submit_cart()
         time.sleep(1)
         robot.close()
Exemplo n.º 3
0
    def test_store_cookie(self):
        driver = self.driver

        # get Your langauge droptown as instance of Select class
        select_language = Select(self.driver.find_element_by_id(
            "select-language"
        ))

        # check default selected option is English
        self.assertEqual(
            "ENGLISH",
            select_language.first_selected_option.text
        )

        # store cookie should be none
        store_cookie = driver.get_cookie("store")
        print("\nCookie is: ")
        print(store_cookie)
        self.assertEqual(None, store_cookie)

        # select option using select_y_visible text
        select_language.select_by_visible_text("French")

        # store cookie should be populated with selected country
        store_cookie = driver.get_cookie("store")['value']
        print("\nCookie is: ")
        print(store_cookie)
        self.assertEqual(
            "french",
            store_cookie
        )
    def test_dropdown_selection(self):
        # Navegamos hasta la aplicacion
        self.driver.get("http://the-internet.herokuapp.com/dropdown")

        select = Select(self.driver.find_element_by_id("dropdown"))

        select.select_by_visible_text("Option 2")
Exemplo n.º 5
0
def makeselection():
	month = browser.find_element_by_xpath(".//a[contains(@onclick, 'jmpto1605')]")
	month.send_keys("\n")
	time.sleep(5) # delays for 5 seconds
	sectionDatesOfStay = browser.find_element_by_id('sectionDatesOfStay')
	containerDatesOfStay = sectionDatesOfStay.find_element_by_id('containerDatesOfStay')
	calCell = containerDatesOfStay.find_element_by_class_name('calCell')
	cal1 = calCell.find_element_by_id('cal1')
	calTable1605 = cal1.find_element_by_id('calTable1605')

	# Select May 28 as the arrival day
	date_28 = calTable1605.find_element_by_id('160528')
	date_28.send_keys("\n")
	time.sleep(5) # delays for 5 seconds

	# Select May 29 as the departure day
	date_29 = calTable1605.find_element_by_id('160529')
	date_29.send_keys("\n")
	time.sleep(5) # delays for 5 seconds

	# Select the adults number
	frmNumAdults = browser.find_element_by_id('frmNumAdults')
	adultNo = Select(frmNumAdults)
	adultNo.select_by_visible_text('2')

	# Check the room status
	time.sleep(5)
	suiteTypes = browser.find_element_by_id('suiteTypes')
	sendemail()
Exemplo n.º 6
0
def step_impl(context):
    window_parent = context.browser.current_window_handle
    window_popup = context.browser.window_handles[-1]
    element = context.browser.find_element_by_xpath("//div[@class='col-sm-10']/p[8]/a")
    element.click()
    context.browser.implicitly_wait(5)
    context.browser.switch_to.window(window_popup)
    element = context.browser.find_element_by_xpath("//div[@id='div_id_course_name']/input")
    element.send_keys("Course name")
    element = context.browser.find_element_by_xpath("//div[@id='div_id_course_id']/input")
    element.send_keys("Course id")
    element = context.browser.find_element_by_xpath("//div[@id='div_id_school_name']/input")
    element.send_keys("School name")
    element = context.browser.find_element_by_id('id_academic_content_area')
    select = Select(element)
    select.select_by_visible_text("Physiology and Pharmacology")
    element = context.browser.find_element_by_xpath("//div[@id='div_id_hours']/input")
    element.clear()
    element.send_keys('45')
    element = context.browser.find_element_by_id('id_grade')
    select = Select(element)
    select.select_by_visible_text("A")
    element = context.browser.find_element_by_xpath("//div[@id='div_id_completion_date']/input")
    element.send_keys("11/20/14")
    element = context.browser.find_element_by_xpath("//div[@class='form_block']/a[1]/span")
    element.click()
    context.browser.switch_to.window(window_parent)
Exemplo n.º 7
0
	def WebConfig(self):
		self.pubmodul.location("/html/frameset/frameset/frame[2]")
		select=Select(self.driver.find_element_by_id("glbl_ena"))
		select.select_by_visible_text("Enabled")
		age=str(random.randint(10,10000000))
		self.driver.find_element_by_id("aging_enabled").click()
		self.driver.find_element_by_id("aging_period").clear()
		self.driver.find_element_by_id("aging_period").send_keys(age)
		config = {}
		config['age']=age
		if self.prjName == 's3280':
			j=9
		if self.prjName == 's4140':
			j=5
		for i in range (1,j):
			config[i]={}
			ena=str("ena_%d"%i)
			select1=Select(self.driver.find_element_by_id(ena))
			select1.select_by_value("1")
			limit_value=str(random.randint(1,1024))

			limit=str("limit_%d"%i)
			config[i]['limit']=limit_value
			self.driver.find_element_by_id(limit).clear()
			self.driver.find_element_by_id(limit).send_keys(limit_value)
			action=str('action_%d'%i)
			action_value=random.choice(['0','1','2','3'])
			config[i]['action']=action_value
			select2=Select(self.driver.find_element_by_id(action))
			select2.select_by_value(action_value)
			time.sleep(1)
		self.driver.find_element_by_xpath("/html/body/form/p/input[2]").click()
		time.sleep(2)
		return config
Exemplo n.º 8
0
 def test_signup(self):
     self.selenium.get('%s%s' % (self.live_server_url, '/user/signup/'))
     self.selenium.find_element_by_name('email').send_keys(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)) + "@mailinator.com")
     self.selenium.find_element_by_name('username').send_keys(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)))
     self.selenium.find_element_by_name('password1').send_keys(password)
     self.selenium.find_element_by_name('password2').send_keys(password)
     self.selenium.find_element_by_name('terms').click()
     self.selenium.find_element_by_name('terms').submit()
     self.selenium.find_element_by_class_name('button').click()
     sex_options = self.selenium.find_elements_by_name('sex')
     option_other = [element for element in sex_options if element.get_attribute('value') == 'male'][0]
     option_other.click()
     self.selenium.find_element_by_name('birthdate_0').send_keys('12')
     self.selenium.find_element_by_name('birthdate_1').send_keys('12')
     self.selenium.find_element_by_name('birthdate_2').send_keys('1212')
     select = Select(self.selenium.find_element_by_name('country'))
     # select.deselect_all()
     select.select_by_visible_text('Other')
     select = Select(self.selenium.find_element_by_name('organization'))
     select.select_by_visible_text('No organization')
     self.selenium.find_element_by_name('description').send_keys(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)))
     self.selenium.find_element_by_name('description').submit()
     # time.sleep(60)
     self.selenium.find_element_by_name('topic_ids[]').click()
     self.selenium.find_element_by_name('topic_ids[]').submit()
     trainingbit_names = [element.text for element in self.selenium.find_elements_by_class_name('trainingbit-name')]
     self.assertIn("Punch an angry shark", trainingbit_names)
     self.assertIn("Run away from trouble", trainingbit_names)
     skill_names = [element.text for element in self.selenium.find_elements_by_name('skill-name')]
     self.assertIn("RESCUING PANDAS FROM FIRE", skill_names)
     self.assertIn("CLEANING NUCLEAR WASTE", skill_names)
  def test_04_dep_bar_content(self):
    chart_titles = ['VistA Packages Dependencies Chart','VistAPackageStatistics']
    dep_chart_legend = ['depends','dependents']
    dep_chart_top_entries = ['Kernel','Order Entry Results Reporting','Accounts Receivable']
    global driver

    # Ensure that the data and labels of chart are not empty
    chart_container = driver.find_elements_by_class_name("highcharts-series")
    for type in chart_container:
      bar_array = type.find_elements_by_tag_name("rect")
      self.assertTrue(len(bar_array) > 0)

    chart_container = driver.find_elements_by_class_name("highcharts-data-labels")
    for type in chart_container:
      bar_array = type.find_elements_by_tag_name("text")
      self.assertTrue(len(bar_array) > 0)


    # Read title of graph
    bar_chart = driver.find_element_by_id("bar-chart")
    title_element = bar_chart.find_element_by_class_name("highcharts-title")
    self.assertTrue(title_element.text in chart_titles)
    # Ensure that legends have proper information
    chart_legend = bar_chart.find_element_by_class_name("highcharts-legend")
    legend_array = chart_legend.find_elements_by_tag_name("text")
    for item in legend_array:
       self.assertTrue(item.get_attribute("innerHTML") in dep_chart_legend)

    # Check each of the "Sort By" selections to ensure that the first element is found in top_entries array
    dep_pulldown = bar_chart.find_element_by_id("list-dep")
    pulldown_options = Select(dep_pulldown)
    for option in pulldown_options.options:
      pulldown_options.select_by_visible_text(option.text)
      self.assertTrue( driver.find_element_by_xpath("//*[@id='highcharts-0']/div/span[1]").text in dep_chart_top_entries)
      time.sleep(5)
Exemplo n.º 10
0
    def fill_out_credit_card(self):
        # User selects credit card option
        ccard = self.driver.find_element_by_id('p_method_cryozonic_stripe')
        ccard.click()

        # User enters Name
        self.driver.find_element_by_id('cryozonic_stripe_cc_owner').clear()
        ccname = self.driver.find_element_by_id('cryozonic_stripe_cc_owner')
        ccname.send_keys('Rebecca Crane')

        # User enters CC number
        self.driver.find_element_by_id('cryozonic_stripe_cc_number').clear()
        ccnum = self.driver.find_element_by_id('cryozonic_stripe_cc_number')
        ccnum.send_keys('4242424242424242')

        # User selects expiration date
        month = Select(
            self.driver.find_element_by_id('cryozonic_stripe_expiration'))
        month.select_by_visible_text('03 - March')

        year = Select(
            self.driver.find_element_by_id('cryozonic_stripe_expiration_yr'))
        year.select_by_visible_text('2022')

        # User enters cvv number
        self.driver.find_element_by_id('cryozonic_stripe_cc_cid').clear()
        cvv = self.driver.find_element_by_id('cryozonic_stripe_cc_cid')
        cvv.send_keys('123')

        # User sees Review section with shipping cost added
        print('Credit card was added. Review section updating')
Exemplo n.º 11
0
def select_multi_items(self, select_name):
    """
    Select multiple options from select with label (recommended), name, or
    id. Pass a multiline string of options. e.g.

    .. code-block:: gherkin

        When I select the following from "Contact Methods":
            \"\"\"
            Email
            Phone
            Fax
            \"\"\"
    """
    # Ensure only the options selected are actually selected
    option_names = self.multiline.split('\n')
    select_box = find_field(world.browser, 'select', select_name)
    assert select_box, "Cannot find a '{}' select.".format(select_name)

    select = Select(select_box)
    select.deselect_all()

    for option in option_names:
        try:
            select.select_by_value(option)
        except NoSuchElementException:
            try:
                select.select_by_visible_text(option)
            except NoSuchElementException:
                raise AssertionError("Cannot find option: '{}'.".format(option))
Exemplo n.º 12
0
 def select_state(self, state):
     select = Select(self.driver.find_element(*ShippingPageLocators.STATE_DROPDOWN))
     if state==None:
         state_number = randint(0,49)
         select.select_by_index(state_number)
     else:
         select.select_by_visible_text(state)
Exemplo n.º 13
0
def boostme(driver,NotAmped,amptype,doubledipchoice):

	if amptype=='DD':

		for k,v in NotAmped.iteritems():

			v.click()
			time.sleep(SLEEP_SECONDS)

			sele=Select(driver.find_element_by_xpath("//*[@id='secondPool']/div/div/div[2]/form/div/select"))
			dropdown_options = sele.options

			
			for available in range(0,len(dropdown_options)):
				current_option=dropdown_options[available].text

				if doubledipchoice==current_option:
					sele.select_by_visible_text(current_option)
					time.sleep(SLEEP_SECONDS)
					break
			SecondPoolDiv=driver.find_element_by_id("secondPool")

			SecondPoolDiv.find_element_by_xpath(".//button[contains(text(), 'Add Pool')]").click()

			time.sleep(SLEEP_SECONDS)
	
	elif amptype=='Boost':
		
		for k,v in NotAmped.iteritems():
			v.click()
			time.sleep(5)
Exemplo n.º 14
0
    def test_generate_by_whiteboard(self):
        b = self.browser
        b.get(get_server_base() + 'matrix/')
        Select(b.find_element_by_name('whiteboard'))\
            .select_by_visible_text(self.job_whiteboard)
        b.find_element_by_xpath('//button[text()="Generate"]').click()
        b.find_element_by_xpath('//table[@id="matrix_datagrid"]'
                '//td[normalize-space(string(.))="Pass: 1"]')
        with session.begin():
            new_job = data_setup.create_completed_job(
                whiteboard=self.job_whiteboard, result=TaskResult.pass_,
                recipe_whiteboard=self.recipe_whiteboard)
        b.find_element_by_xpath('//button[text()="Generate"]').click()
        b.find_element_by_xpath('//table[@id="matrix_datagrid"]'
                '//td[normalize-space(string(.))="Pass: 2"]')

        #Try with multiple whiteboards
        with session.begin():
            another_new_job = data_setup.create_completed_job(
                whiteboard=self.job_whiteboard_2, result=TaskResult.pass_,
                recipe_whiteboard=self.recipe_whiteboard)
        b.get(get_server_base() + 'matrix/')
        whiteboard = Select(b.find_element_by_name('whiteboard'))
        whiteboard.select_by_visible_text(self.job_whiteboard)
        whiteboard.select_by_visible_text(self.job_whiteboard_2)
        b.find_element_by_xpath('//button[text()="Generate"]').click()
        b.find_element_by_xpath('//table[@id="matrix_datagrid"]'
                '//td[normalize-space(string(.))="Pass: 3"]')
Exemplo n.º 15
0
 def select_state(self, country):
     select = Select(self.driver.find_element(*ShippingPageLocators.STATE_DROPDOWN))
     if country==None:
         random = randint(0,3)
         select.select_by_index(state_number)
     else:
         select.select_by_visible_text(country)
Exemplo n.º 16
0
 def select_current_climate_layers(self, resolution, string):
     # select the correct resolution filter
     select = Select(self.driver.find_element_by_name("form.widgets.resolution:list"))
     select.select_by_visible_text(resolution)
     # Yes, there is a type here, but that's how it is on the backend
     path_string = "(//tr[@data-friendlyname='collapbsable_climatelayer_" + string + "'])"
     self.driver.find_element_by_xpath(path_string).click()
Exemplo n.º 17
0
    def _open_all_the_tables():
        refresh_window(world)
        pagers = get_elements(world.browser, class_attr="gridview", tag_name="table")
        pagers = filter(lambda x : x.is_displayed(), pagers)
        for pager in pagers:
            elem = get_element(pager, class_attr="pager_info", tag_name="span")

            m = re.match('^\d+ - (?P<from>\d+) of (?P<to>\d+)$', elem.text.strip())
            do_it = False

            if m is None:
                do_it = True
            else:
                gp = m.groupdict()
                do_it = gp['from'] != gp['to']

            if do_it:
                elem.click()

                # we cannot select an unlimited number of items. So we stick to 500
                #  even if we know that the row we are looking for is in the next page... (comes from US-1207)
                element = get_element(pager, tag_name="select", attrs=dict(action="filter"))
                select = Select(element)
                select.select_by_visible_text("500")

                wait_until_not_loading(world.browser, wait="I cannot load the whole table")
Exemplo n.º 18
0
    def _test_fxa_signup(self):
        '''FullFlow1:create, signout - %s %s %s''' % \
        (self.os, self.br, self.version)

        self.driver.get(FXA_SIGNUP)
        time.sleep(2)
        assert 'Create' in self.driver.title

        username = self.driver.find_element_by_css_selector(input_email)
        username.send_keys(self.fxa_new_user)
        time.sleep(2)
        pw = self.driver.find_element_by_css_selector(input_password)
        pw.send_keys(fxa_password)

        selectBox = Select(self.driver.find_element_by_id(coppa_locator))
        time.sleep(2)
        selectBox.select_by_visible_text("1991")

        self.driver.find_element_by_id(btn_submit).click()

        self.wait_page_load(FXA_SIGNUP)
        assert 'Confirm your account' in self.driver.title

        # verify restmail user
        time.sleep(4)
        restmail_link = getRestmailLink(self.fxa_new_user)
        self.driver.get(restmail_link)
        time.sleep(2)
        assert 'verified' in self.driver.title
Exemplo n.º 19
0
    def test_language_options(self):
        # list of expected values in Language dropdown
        exp_options = ["ENGLISH", "FRENCH", "GERMAN"]

        # empty list for capturing actual options displayed # in the dropdown
        act_options = []

        # get the Your language dropdown as instance of Select class
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))

        # check number of options in dropdown
        self.assertEqual(2, len(select_language.options))

        # get options in a list
        for option in select_language.options:
            act_options.append(option.text)

        # check expected options list with actual options list
        self.assertListEqual(exp_options, act_options)

        # check default selected option is English
        self.assertEqual("ENGLISH", select_language.first_selected_option.text)

        # select an option using select_by_visible text
        select_language.select_by_visible_text("German")

        # check store is now German
        self.assertTrue("store=german" in self.driver.current_url)

        # changing language will refresh the page,
        # we need to get find language dropdown once again
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))
        select_language.select_by_index(0)
Exemplo n.º 20
0
    def bulkCreate(self):
        self.log.write("namepefix id" +self.guestNamePefix)
        self.browser.find_element_by_xpath("//*[@id='guestName']").send_keys(self.guestNamePefix)
        self.browser.find_element_by_xpath("//*[@id='userProfile']").clear()
        self.log.write("guestnumber is"+self.guestNumber)
        self.browser.find_element_by_xpath("//*[@id='userProfile']").send_keys(self.guestNumber)
        self.log.write("select guest type,guest type is"+self.guestType)
        select = Select(self.browser.find_element_by_xpath("//*[@name='authType']")) 
        select.select_by_visible_text(self.guestType)
        time.sleep(2)
#         //*[@id="J-create"]
        self.log.write("click 'create'")
        self.browser.find_element_by_xpath("//a[@id='J-create']").click()
        time.sleep(2)
        self.guestinfo.append("Wi-Fi Network:")
        self.guestinfo.append(self.browser.find_element_by_xpath("//form[@id='guest-two-form']/fieldset/table/tbody/tr/td[2]/p").text)
        self.guestinfo.append("Prefix for Guest Names:")
        self.guestinfo.append(self.browser.find_element_by_xpath("//form[@id='guest-two-form']/fieldset/table/tbody/tr[2]/td[2]/p").text)
        self.guestinfo.append("Number of Guests:")
        self.guestinfo.append(self.browser.find_element_by_xpath("//form[@id='guest-two-form']/fieldset/table/tbody/tr[3]/td[2]/p").text)
        self.guestinfo.append("Access Duration:")
        self.guestinfo.append(self.browser.find_element_by_xpath("//form[@id='guest-two-form']/fieldset/table/tbody/tr[4]/td[2]/p").text)
        self.browser.find_element_by_xpath("//*[@id='deliver-name']").send_keys(self.email)
        self.log.write("click 'comfirm'")
        self.browser.find_element_by_xpath("/html/body/div/div[2]/div[2]/div[2]/div/form/fieldset[2]/table/tbody/tr[3]/td[2]/p/a").click()
        time.sleep(2)
Exemplo n.º 21
0
    def createGuest(self):
#         self.gotoCreateGuest(self)
#         self.browser.find_element_by_xpath("/html/body/div/div[2]/div[2]/div/div[2]/div/div/p[2]/a").click()
        time.sleep(2)
        self.log.write("guetname is "+self.guestName)
        self.browser.find_element_by_xpath("//*[@id='guestName']").send_keys(self.guestName)
        self.log.write("organization is" +self.organization)
        self.browser.find_element_by_xpath("//*[@id='organization']").send_keys(self.organization)
        self.log.write("purpose is"+self.purposeOfVisit)
        self.browser.find_element_by_xpath("//*[@id='visitPurpose']").send_keys(self.purposeOfVisit)
        self.log.write("email is "+self.email)
        self.browser.find_element_by_xpath("//*[@id='email']").send_keys(self.email)
        self.log.write("phone is" +self.phone)
        self.browser.find_element_by_xpath("//*[@id='phoneNumber']").send_keys(self.phone)
        self.log.write("the type of logname is"+self.loginName)
        self.browser.find_element_by_xpath("//input[@value='"+self.loginName+"']").click()
#         logname:email,phone,name
        self.log.write("select guesttype" +self.guestType)
        select = Select(self.browser.find_element_by_xpath("//*[@id='J-guest-type']")) 
        select.select_by_visible_text(self.guestType)
        self.log.write("click 'create'")
        self.browser.find_element_by_xpath("//*[@id='J-next']").click()
#         guestSsid=self.browser.find_elenment_by_xpath("//form[@id='new-gt-form']/fieldset[3]/table/tbody/tr[2]/td[2]/p[2]/span").text
#         self.browser.find_element_by_xpath("//form[@id='new-gt-form']/fieldset[3]/table/tbody/tr[4]/td[2]/p/a").click()
        
#         self.guestloginName=self.browser.find_element_by_xpath("/html/body/div[6]/div/div/form/fieldset/table/tbody/tr[2]/td[2]/p").text
#         self.guestpasswd=self.browser.find_element_by_xpath("/html/body/div[6]/div/div/form/fieldset/table/tbody/tr[3]/td[2]/p").text
#         self.accessTime=self.browser.find_element_by_xpath("/html/body/div[6]/div/div/form/fieldset/table/tbody/tr[4]/td[2]/p").text
#         self.sendEmail=self.browser.find_element_by_path("//*[@id='deliver-name']").text  
        time.sleep(2)
        self.log.write("click 'confirm'")
        self.browser.find_element_by_xpath("/html/body/div/div[2]/div[2]/div[2]/div/form/fieldset[2]/table/tbody/tr[3]/td[2]/p/a").click()
                                                 
#         self.browser.find_element_by_xpath("/html/body/div[6]/div/div/form/fieldset[2]/table/tbody/tr[3]/td[2]/p/a").click()
        time.sleep(2)
Exemplo n.º 22
0
def create_csv(year,month):
	path = os.getcwd()+os.sep+"temp"
	profile = webdriver.FirefoxProfile()
	profile.set_preference('browser.download.folderList', 2) # custom location
	profile.set_preference('browser.download.manager.showWhenStarting', False)
	profile.set_preference('browser.download.dir', path)
	profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')
	driver = webdriver.Firefox(profile)
	try:
		driver.get("https://www.ura.gov.sg/realEstateIIWeb/price/search.action")
		driver.implicitly_wait(5)
		select_year = Select(driver.find_element_by_name('yearSelect'))
		onchange_null  = "document.getElementById('yearSelect').onchange='';document.getElementById('monthSelect').onchange='';"
		clear_month = "$('#monthSelect').empty();"
		append_month = "$('#monthSelect').append(\"<option selected='selected' value="+str(month)+">"+str(month)+"</option>\");"  
		driver.execute_script(clear_month)
		driver.execute_script(onchange_null)
		driver.execute_script(append_month)
		select_year.select_by_visible_text(year)
		driver.execute_script("submitViewAll()")
		driver.implicitly_wait(5)
		driver.get("https://www.ura.gov.sg/realEstateIIWeb/price/submitExcelResults.action")
		print(year,month)
		driver.close()
	except:
		print("Logging missed values")
		print(year,month)
		print(sys.exc_info())
		log.append([year,month])
		driver.implicitly_wait(10)
Exemplo n.º 23
0
def getLinks(topic, collection, driver):
	startPage = "http://www.cochranelibrary.com/home/topic-and-review-group-list.html?page=topic"
	# Clicking on given topic
	driver.get(startPage)
	# Loading the page
	driver.find_element_by_link_text(topic).click()
	# Waiting until page is loaded
	numberSelector = WebDriverWait(driver, 1).until(
        EC.presence_of_element_located((By.ID, "results_per_page_top"))
    )

	select = Select(numberSelector)
	# Loading 100 element on the page
	select.select_by_visible_text("100")
	time.sleep(3)

	# Gettin page number 
	pageNext = driver.find_element_by_class_name("results-block__pagination-list")
	listPage = pageNext.find_elements_by_tag_name("li")

	for i in range(len(listPage)-1):
		getLinksSinglePage(collection, driver)

		pageNext = driver.find_element_by_class_name("results-block__pagination-list")
		listPage = pageNext.find_elements_by_tag_name("li")

		# Click on next button
		listPage[-1].click()
		time.sleep(10)
Exemplo n.º 24
0
def add_dlpfile():
        dlpdict= {"filenameNoIP":u"文件.txt"}

        for key in dlpdict.keys():
                login(driver,user,base_url)
                dlpname = str(key)
                value = dlpdict.get(key)
                time.sleep(3)
                yigou=driver.find_element_by_xpath(u"//span[contains(text(), '策略管理')]")
                ActionChains(driver).move_to_element(yigou).perform()
                driver.find_element_by_xpath("//a[@href='#/policy/manager']").click()
                time.sleep(3)
                driver.find_element_by_xpath(u"//div[contains(text(), 'DLP策略')]").click()
                driver.find_element_by_xpath(u"//span[contains(text(), '新增')]").click()
                driver.find_element_by_id("policyname").clear()
                driver.find_element_by_id("policyname").send_keys("%s" %(dlpname))
                time.sleep(2)
                driver.find_element_by_xpath("(//button[@type='button'])[2]").click()
                driver.find_element_by_xpath("(//button[@type='button'])[4]").click()
                select = Select(driver.find_element_by_xpath(u"//select[contains(@id, 'policytype_')]"))
                select.select_by_visible_text(u"文件名")
                driver.find_element_by_xpath(u"//div[@class='col-md-8']/div[@class='form-group']/input").send_keys("%s" %(value))
                time.sleep(3)
                driver.find_element_by_xpath(u"//span[contains(text(),'生成安全事件')]").click()
                driver.find_element_by_id("alertname").send_keys("%s" %(dlpname))
                Select(driver.find_element_by_id("alertseverity")).select_by_visible_text(u"极度严重")
                Select(driver.find_element_by_id("alertcategory")).select_by_visible_text(u"有害程序")
                driver.find_element_by_css_selector("#alertcategory > option.ng-binding.ng-scope").click()
                Select(driver.find_element_by_id("alertsubcategory")).select_by_visible_text(u"网页恶意代码")
                driver.find_element_by_xpath(u"//div/button[contains(text(), '提交')]").click()
                time.sleep(5)
Exemplo n.º 25
0
 def add_in_group(self, contact, group):
     wd = self.app.wd
     self.open_home_page()
     self.select_contact_by_id(contact.id)
     select = Select(wd.find_element_by_name("to_group"))
     select.select_by_visible_text(group.name)
     wd.find_element_by_name("add").click()
Exemplo n.º 26
0
	def test_editor_can_create_new_media_item(self):

		# Anthony logs into the site
		self.log_in_editor()

		# Anthony goes to the add new story page
		self.browser.get(self.test_server + '/story/add/media')

		# Anthony tries to save the media item without a title, but can't 
		self.browser.find_element_by_id('id_title').clear()
		self.browser.find_element_by_name('submit').click()
		self.assertIn('This field is required.', self.browser.find_element_by_class_name('help-block').text)

		# Anthony makes some changes and saves.
		self.browser.find_element_by_id('id_title').send_keys('Functional Test Add Media Title')
		self.browser.find_element_by_class_name('redactor_editor').send_keys('This is an added paragraph to the create new story test.')
		author = Select(self.browser.find_element_by_id('id_author'))
		author.select_by_visible_text('anthony')
		self.browser.find_element_by_id('id_tags').send_keys(', Tags, Media')

		self.browser.find_element_by_name('submit').click()

		# Anthony sees two success messages, saved and editor notified
		self.assertIn('Media saved successfully', 
						self.browser.find_elements_by_class_name('alert-success')[0].text)
		self.assertIn('Functional Test Add Media Title',
						self.browser.find_element_by_tag_name('h2').text)
Exemplo n.º 27
0
 def set_experience(self):
     if len(self.driver.find_elements_by_css_selector(
             '.recommended-section-experience > .recommended-section-add')) > 0:
         self.driver.find_element_by_css_selector(
             '.recommended-section-experience > .recommended-section-add').click()
     elif len(self.driver.find_elements_by_css_selector('#background-experience > button')) > 0:
         self.driver.find_element_by_css_selector('#background-experience > button').click()
     else:
         return False
     time.sleep(1)
     # company name
     self.driver.find_element_by_css_selector('#companyName-positionCompany-position-editPositionForm').send_keys(
         self.profile.organization)
     time.sleep(1)
     # title
     self.driver.find_element_by_css_selector('#title-position-editPositionForm').send_keys(self.profile.title)
     # time period
     select = Select(self.driver.find_element_by_css_selector('#month-startDate-position-editPositionForm'))
     select.select_by_visible_text(self.profile.start_month)
     self.driver.find_element_by_css_selector('#year-startDate-position-editPositionForm').clear()
     self.driver.find_element_by_css_selector('#year-startDate-position-editPositionForm').send_keys(
         self.profile.start_year)
     self.driver.find_element_by_css_selector('#isCurrent-endDate-position-editPositionForm').click()
     self.driver.find_element_by_css_selector('#summary-position-editPositionForm').send_keys(
         self.profile.description)
     self.driver.find_element_by_css_selector('form[name=editPositionForm] > p > input').click()
Exemplo n.º 28
0
	def test_drop_down(self):
		driver = self.driver
		
		exp_options = [ "BMW", "Mercedes", "Audi", "Honda" ]
		act_options = []
		
	 	#Get the Dropdown as a Select using it's name attribute
 		make = Select(driver.find_element_by_name("make"))
		
		#Verify Dropdown has four options for selection
		self.assertEqual(4,len(make.options))
    	
		#Retrieve the option values from Dropdown using getOptions() method
		for option in make.options:
			act_options.append(option.text)
		
		#Verify Dropdown has four options for selection
		self.assertEqual(exp_options,act_options)
		
		#With Select class we can select an option in Dropdown using Visible Text
		make.select_by_visible_text("Honda")
		self.assertEqual("Honda",make.first_selected_option.text)
    	
		#or we can select an option in Dropdown using value attribute
		make.select_by_value("audi")
		self.assertEqual("Audi",make.first_selected_option.text)
		
		#or we can select an option in Dropdown using index
		make.select_by_index("0")
		self.assertEqual("BMW",make.first_selected_option.text)
Exemplo n.º 29
0
    def get_entries(self):
        selected = self.soup.find(class_="journal")
        journal_select = Select(self.driver.find_element_by_id("journal"))

        # getting rid of first "description" row
        journal_gen = WileyScraper.__get_child_tag_strings(selected)
        next(journal_gen)

        for journal in journal_gen:
            try:
                journal_select.select_by_visible_text(journal)
            except NoSuchElementException:
                print "Couldn't find matching journal for input: " + str(journal)
                continue

            oa_option_element = self.driver.find_element_by_id("displayJOAP")

            if (oa_option_element.text == "Fully Open Access") or (oa_option_element.text == "OpenChoice"):

                try:
                    price = self.__get_price()
                except MissingAttributeException:
                    print journal + ": Unable to find price"
                    continue
                try:
                    issn_matches = self.__get_issn()
                except MissingAttributeException:
                    print "Error: " + journal + "\n\t" + oa_option_element.text
                    continue

                journal_type = "OA" if oa_option_element.text == "Fully Open Access" else "Hybrid"
                yield self.to_unicode_row(["Wiley", journal, str(date.today()), journal_type, issn_matches, price])
Exemplo n.º 30
0
    def select(self, selector, value):
        from selenium.webdriver.support.ui import Select

        elem = self.selenium.find_element_by_css_selector(selector)
        select = Select(elem)

        select.select_by_visible_text(value)
Exemplo n.º 31
0
d = {}
#states taken from Jacob's weather list
states = ["ALABAMA","ALASKA","ARIZONA","ARKANSAS","CALIFORNIA","COLORADO",
               "CONNECTICUT","DELAWARE","FLORIDA","GEORGIA","HAWAII","IDAHO",
               "ILLINOIS","INDIANA","IOWA","KANSAS","KENTUCKY","LOUISIANA",
               "MAINE","MARYLAND","MASSACHUSETTS","MICHIGAN","MINNESOTA",
               "MISSISSIPPI","MISSOURI","MONTANA","NEBRASKA","NEVADA",
               "NEW HAMPSHIRE","NEW JERSEY","NEW MEXICO","NEW YORK","NORTH CAROLINA",
               "NORTH DAKOTA","OHIO","OKLAHOMA","OREGON","PENNSYLVANIA",
               "RHODE ISLAND","SOUTH CAROLINA","SOUTH DAKOTA","TENNESSEE","TEXAS",
               "UTAH","VERMONT","VIRGINIA","WASHINGTON","WEST VIRGINIA",
               "WISCONSIN","WYOMING"]
#Iteration over dropdown menu "state"
for x in states:
    select = Select(driver.find_element_by_name('state'))
    select.select_by_visible_text(x)

    time.sleep(1)

    Urls = driver.find_elements_by_partial_link_text("wss_SSA")
    new_pop = []
#All for checking; real version would end with a .click() on "wss_SSA"
    for y in Urls:
        y = y.text
        new_pop.append(y)
    d.update({x : new_pop})
df = pd.DataFrame({ key:pd.Series(value) for key, value in d.items() })
print(df)


Exemplo n.º 32
0
#WINDOW_SIZE = "1920,1080"

#firefox_options = Options()
#firefox_options.add_argument("--headless")

options = Options()
options.set_headless(headless=True)

driver = webdriver.Firefox(firefox_options=options)
driver.get(
    'https://www.nseindia.com/live_market/dynaContent/live_watch/pre_open_market/pre_open_market.htm'
)

select = Select(driver.find_element_by_id('selId'))
select.select_by_visible_text('FO Stocks')
time.sleep(2)
data = driver.page_source
driver.close()

NSE_premarket_soup = BeautifulSoup(data, "html.parser")
import re
import operator
if not NSE_premarket_soup.find(string='NIFTY 50'):
    NSE_premarket_trlist = []
    for tr in NSE_premarket_soup.find('table',
                                      id="preOpenNiftyTab").findAll('tr'):
        NSE_premarket_tdlist = []
        if ',' in tr.contents[9].text:
            if float(tr.contents[9].text.replace(',', '')) < 50000:
                if float(tr.contents[8].text.replace(',', '')) > 60:
 def setManagerOfVendor(self, value):
     drp = Select(
         self.driver.find_element_by_xpath(self.drpmgrOfVendor_xpath))
     drp.select_by_visible_text(value)
Exemplo n.º 34
0
    def set_sort_order(self, sort_order):

        select = Select(self.driver.find_element_by_id(ddl_order_by))
        select.select_by_visible_text(sort_order)
Exemplo n.º 35
0
def scrape(br, folder):

    import time
    from selenium.common.exceptions import NoSuchElementException
    from selenium.common.exceptions import StaleElementReferenceException
    import os
    from selenium.webdriver.support.ui import Select

    tab_num = len(br.window_handles)

    phase_list = []
    subject_list = []
    career_list = []
    class_list = []
    text_list = []

    for i in range(0, tab_num):
        phase_list.append(0)
        subject_list.append(int(i * 240 / tab_num))
        career_list.append(0)
        class_list.append(0)
        text_list.append('')

        br.switch_to_window(br.window_handles[i])
        br.get(
            "https://sis.erp.ohio-state.edu/psp/scsosucs/EMPLOYEE/BUCK/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL?"
        )

    tab_index = -1
    done = 0
    while (done == 0):

        tab_index += 1

        if (tab_index == tab_num):
            tab_index = 0

        br.switch_to_window(br.window_handles[tab_index])
        time.sleep(.5)
        br.switch_to_frame("ptifrmtgtframe")

        if phase_list[tab_index] == 0:  #get to add class from main page
            br.get(
                "https://sis.erp.ohio-state.edu/psp/scsosucs/EMPLOYEE/BUCK/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL?"
            )
            br.switch_to_frame("ptifrmtgtframe")
            Add_a_Class_Button = br.find_element_by_link_text("Add a Class")
            Add_a_Class_Button.click()

            phase_list[tab_index] = 1

        elif phase_list[tab_index] == 1:  #look for search button 1
            try:
                Search_Button1 = br.find_element_by_link_text("search")
                Search_Button1.click()
                phase_list[tab_index] = 2
            except NoSuchElementException:
                pass

        elif phase_list[tab_index] == 2:  #perform search
            try:

                Campus_List = Select(
                    br.find_element_by_id("SSR_CLSRCH_WRK_CAMPUS$0"))
                Subject_List = Select(
                    br.find_element_by_id("SSR_CLSRCH_WRK_SUBJECT_SRCH$1"))
                Career_List = Select(
                    br.find_element_by_id("SSR_CLSRCH_WRK_ACAD_CAREER$3"))
                Open_Box = br.find_element_by_name(
                    "SSR_CLSRCH_WRK_SSR_OPEN_ONLY$4")

                Campus_List.select_by_visible_text("Columbus")
                time.sleep(1)

                Subject_List.select_by_index(subject_list[tab_index] + 1)
                time.sleep(1)

                Career_List.select_by_index(career_list[tab_index] + 1)
                time.sleep(1)

                Open_Box.click()
                time.sleep(1)

                SearchButton2 = br.find_element_by_link_text("Search")
                SearchButton2.click()

                career_list[tab_index] += 1

                if (career_list[tab_index] > 7):
                    career_list[tab_index] = 0
                    subject_list[tab_index] += 1

                phase_list[tab_index] = 3

            except NoSuchElementException:
                time.sleep(.05)
            except StaleElementReferenceException:
                time.sleep(.05)

        elif phase_list[tab_index] == 3:  #search results
            try:
                Class_Button0 = br.find_element_by_id("MTG_CLASS_NBR$" +
                                                      str(0))

                try:
                    Class_Button = br.find_element_by_id(
                        "MTG_CLASS_NBR$" + str(class_list[tab_index]))
                    text = Class_Button.text
                    if (os.path.isfile(folder + text + ".txt")):
                        class_list[tab_index] += 1
                    else:
                        text_list[tab_index] = Class_Button.text
                        Class_Button.click()
                        phase_list[tab_index] = 4

                except NoSuchElementException:
                    class_list[tab_index] = 0
                    phase_list[tab_index] = 0

            except NoSuchElementException:
                if (class_list[tab_index] == 0):
                    try:
                        No_Results = br.find_element_by_id(
                            "DERIVED_CLSMSG_ERROR_TEXT")

                        if (No_Results.text ==
                                'Your search will exceed the maximum limit of 300 sections.  Specify additional criteria to continue.'
                            ):
                            print("OVERFLOW ERROR: " +
                                  str(subject_list[tab_index]) + ", " +
                                  str(career_list[tab_index]))

                        Clear_Button = br.find_element_by_link_text("Clear")
                        Clear_Button.click()

                        phase_list[tab_index] = 2

                    except NoSuchElementException:
                        time.sleep(.05)
                else:
                    time.sleep(.05)

        elif phase_list[tab_index] == 4:  #class page
            try:
                Return_Button = br.find_element_by_link_text(
                    "View Search Results")
                innerHTML = br.execute_script("return document.body.innerHTML")
                file = open(folder + text_list[tab_index] + ".txt", "w")
                file.write(innerHTML)
                file.close()

                class_list[tab_index] += 1

                Return_Button.click()
                phase_list[tab_index] = 3
            except NoSuchElementException:
                time.sleep(.05)
Exemplo n.º 36
0
                    EC.element_to_be_clickable((By.CLASS_NAME, "mnuBtn")))
            except Exception as e:
                log("Failed")
                traceback.print_exc(file=file_log)
                flag_e_options = 1
                break

            navigate_click(value)

            main_menu_arrow.click()

        else:
            select = Select(driver.find_element_by_id(main_menu_index))

            # select by visible text
            select.select_by_visible_text(value)

            log(prefix + "Select " + key + " with choice " + value)

    if (flag_e_options):
        break

    #==========================  Other Options =====================================================
    log(prefix + "Fill out Company Name")
    company = driver.find_element_by_id("coTab")
    company.click()

    company_input = driver.find_element_by_id("coTxt")
    company_input.send_keys(company_name)

    enter_search = driver.find_element_by_id("coLkp")
Exemplo n.º 37
0
search = driver.find_element_by_name('q')
search.clear()
search.send_keys('pycon')
search.send_keys(Keys.RETURN)
time.sleep(4)

driver.close()

driver2 = webdriver.Chrome(ChromeDriverManager().install())
driver2.get('file:///Users/antonaleksandrov/test_file.html')
select_elem = Select(driver2.find_element_by_name('numReturnSelect'))
select_elem.select_by_index(2)
time.sleep(2)

select_elem.select_by_visible_text('200')
time.sleep(2)

select_elem.select_by_value('250')
time.sleep(2)

option = select_elem.options
print(option)

submit_button = driver2.find_element_by_name('continue_select')
submit_button.submit()
time.sleep(2)

driver2.close()

# drag and drop
Exemplo n.º 38
0
    def _pipeline(self, roll, sem, sem_year):
        """
        Pipeline for retrieving semester results.

        Parameters
        ----------
        roll : str
            Contains the roll number of an individual student.
        sem : str
            Contains the semester for which the result is required.
        sem_year : str
            Contains the year in which the semester was attended.

        Returns
        -------
        res : dict
            Contains the retrieved result along with the student's information.

        """
        roll = str(roll)
        sem = str(sem)
        sem_year = str(sem_year)
        
        res = {}
        for field in self._result_fields:
            res[field] = "-"
        res["roll"] = roll
        res['success'] = False
        
        self._config.load_config(sem, sem_year)
        config = self._config.config
        
        if config == False:
            print("ERROR: Configuration not loaded.")
            sys.exit()
        else:
            try:
                # Loading url
                self._browser.get(config['url'])
                
                # Inputting roll number
                roll_tb = self._browser.find_element_by_name(
                    config['roll_tb_name'])
                roll_tb.send_keys(roll)
                
                # Selecting semester
                sem_dd = Select(self._browser.find_element_by_name(
                    config['sem_dd_name']))
                sem_dd.select_by_visible_text(sem)
                
                # Submitting form
                submit_bt = self._browser.find_element_by_name(
                    config['submit_bt_name'])
                submit_bt.click()
                
                # Retrieving and cleaning information from webpage
                page_src = self._browser.page_source
                if self._roll_error_msg in page_src:
                    print("ERROR: Result missing for Roll {}.".format(roll))
                else:
                    try:
                        # Fetching roll number
                        res['name'] = self._browser.find_element_by_id(
                            config['name_id'])
                        res['name'] = res['name'].text.replace("Name", "")
                        res['name'] = res['name'].strip()
                        
                        # Fetching roll number
                        res['roll'] = self._browser.find_element_by_id(
                            config['roll_id'])
                        res['roll'] = res['roll'].text.split(" ")[2]
                        
                        # Fetching registration number
                        res['reg'] = self._browser.find_element_by_id(
                            config['reg_id'])
                        res['reg'] = res['reg'].text.split(" ")[2]
                        
                        # Fetching odd semester SGPA
                        res['sgpao'] = self._browser.find_element_by_id(
                            config['sgpao_id'])
                        res['sgpao'] = res['sgpao'].text.split(" ")[3]
                        
                        # Fetching even semester information if available
                        if self._config.sem_type == "EVEN":
                            # Fetching even semester SGPA
                            res['sgpae'] = self._browser.find_element_by_id(
                                config['sgpae_id'])
                            res['sgpae'] = res['sgpae'].text.split(" ")[3]
                            
                            # Fetching YGPA
                            res['ygpa'] = self._browser.find_element_by_id(
                                config['ygpa_id'])
                            res['ygpa'] = res['ygpa'].text.split(" ")[3]
                        
                        res['success'] = True
                        
                    except NoSuchElementException:
                        res['success'] = False
                        print("ERROR: Invalid configuration file.")
                        sys.exit()
                        
            except WebDriverException:
                print("ERROR: Cannot reach URL.")
                sys.exit()
            except NoSuchElementException:
                print("ERROR: Invalid configuration file.")
                sys.exit()
            except:
                traceback.print_exc()
                print("ERROR: An unexpected error has occurred.")
                sys.exit()
        
        return res
Exemplo n.º 39
0
def run_315(accounts,sub,year,freq,sourcevar):
    print ("Pulling a total of {0} reports.".format(len(accounts*(1 if freq==0 else 2 if freq==1 else 4 if freq==2 else 12))))

    msg = "Run 315 Reports"
    title = "IDS credentials"
    fieldNames = ["IDS username", "IDS password"]
    fieldValues = []  # we start with blanks for the values
    fieldValues = multpasswordbox(msg, title, fieldNames)

    # make sure that none of the fields was left blank
    while 1:
        if fieldValues == None: break
        errmsg = ""
        for i in range(len(fieldNames)):
            if fieldValues[i].strip() == "":
                errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
        if errmsg == "": break  # no problems found
        fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)


    driver = webdriver.Chrome("Resources/chromedriver.exe")
    driver.get("http://idssprd.cusa.canon.com/")
    driver.find_element_by_name("user").send_keys(fieldValues[0])
    driver.find_element_by_name("password").send_keys(fieldValues[1])
    driver.find_element_by_name("login").send_keys(Keys.RETURN)


    main_sub=True if sub=='CUSR0315' else False
    companies=True if sub=="CSAR0315" else False

    if (main_sub):
        from_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/input[1]"
        to_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/input[2]"
        act_from_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/input[3]"
        act_to_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/input[4]"
    else:
        from_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/input[1]"
        to_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/input[2]"
        act_from_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/select[1]"
        act_to_path = "/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[2]/select[2]"

    counter = 0
    start = datetime.datetime.now()

    if (freq == 0):
        dates_start = ["01/{0}".format(year)]
        dates_end = ["12/{0}".format(year)]

    elif (freq == 1):
        dates_start = ["01/{0}".format(year), "07/{0}".format(year)]
        dates_end = ["06/{0}".format(year), "12/{0}".format(year)]

    elif (freq == 2):
        dates_start = ["01/{0}".format(year), "04/{0}".format(year), "07/{0}".format(year), "10/{0}".format(year)]
        dates_end = ["03/{0}".format(year), "06/{0}".format(year), "09/{0}".format(year), "12/{0}".format(year)]

    else:
        dates_start = ["01/{0}".format(year), "02/{0}".format(year), "03/{0}".format(year), "04/{0}".format(year) \
            , "05/{0}".format(year), "06/{0}".format(year), "07/{0}".format(year), "08/{0}".format(year) \
            , "09/{0}".format(year), "10/{0}".format(year), "11/{0}".format(year), "12/{0}".format(year)]
        dates_end = ["01/{0}".format(year), "02/{0}".format(year), "03/{0}".format(year), "04/{0}".format(year) \
            , "05/{0}".format(year), "06/{0}".format(year), "07/{0}".format(year), "08/{0}".format(year) \
            , "09/{0}".format(year), "10/{0}".format(year), "11/{0}".format(year), "12/{0}".format(year)]


    for account in accounts:
        for j in range(len(dates_start)):

            driver.get("http://idssprd.cusa.canon.com/scripts/rds/cgionline.exe?program_id=CSLMENU&rt=0&PARA=")
            top_level = driver.find_element_by_xpath('//*[@id="mnu-Main"]/li[3]')
            driver.execute_script("arguments[0].setAttribute('class','mnuopen')", top_level)
            for folder in range(1, 16):
                driver.execute_script("arguments[0].setAttribute('class','mnuopen')", \
                                      driver.find_element_by_xpath('//*[@id="mnu-FINORACLE"]/li[{0}]'.format(folder)))

            driver.find_element_by_partial_link_text(sub).click()

            for i in range(7):
                driver.find_element_by_xpath(from_path).send_keys(Keys.BACKSPACE)
            driver.find_element_by_xpath(from_path).send_keys(dates_start[j])

            for i in range(7):
                driver.find_element_by_xpath(to_path).send_keys(Keys.BACKSPACE)
            driver.find_element_by_xpath(to_path).send_keys(dates_end[j])

            driver.find_element_by_xpath(act_from_path).send_keys(str(account))
            driver.find_element_by_xpath(act_to_path).send_keys(str(account))

            if main_sub or sub in ["CFSR0315","CISR0315","CPAR0315"]:
                select = Select(driver.find_element_by_xpath(
                    '/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[4]/select[4]'))
            else:
                select = Select(driver.find_element_by_xpath(
                    '/html/body/table[1]/tbody/tr[3]/td/form/table/tbody/tr/td[4]/select[2]'))

            select.select_by_visible_text(sourcevar.get())
            driver.find_element_by_xpath('//*[@id="submit_run"]/img').click()
            counter += 1
    time_rn = datetime.datetime.now() - start
    print(time_rn.total_seconds())
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(10)
driver.get("https://www.orangehrm.com/orangehrm-30-day-trial/")
driver.maximize_window()
country = driver.find_element(By.ID, "Form_submitForm_Industry")
Select = Select(country)
Select.select_by_visible_text("Education")
time.sleep(5)
driver.quit()
Exemplo n.º 41
0
    def test_create_a_new_text(self):
        language_1 = LanguagesFactory(owner=self.user_1)
        self.selenium.get('{}/text_detail/?new=0/'.format(
            self.live_server_url))
        select = Select(self.find(By.NAME, 'language'))
        select.select_by_visible_text(self.language_1.name)
        title_str = 'an Example of title'
        title = self.find(By.NAME, 'title')
        title.send_keys(title_str)
        text = self.find(By.NAME, 'text')
        text.send_keys('This is the content of this text.')
        save = self.find(By.ID, 'submit-id-save')
        save.click()
        #         time.sleep(5)
        #         self.selenium.implicitly_wait(10)
        #         self.wait_until(By.ID, 'text_table')
        self.selenium.get('{}/text_list/'.format(self.live_server_url))
        self.assertEqual(self.selenium.current_url,
                         '{}/text_list/'.format(self.live_server_url))
        self.find(By.CSS_SELECTOR, '#filterlangform input[value="2"]').click()
        self.wait_until_disappear(
            By.XPATH, '//td[contains(text(), "No matching records found")]')
        self.wait_until_appear(
            By.XPATH, '//td[contains(text(), "an Example of title")]')
        texts = self.finds(By.CSS_SELECTOR, '#text_table tbody tr')
        self.assertEqual(len(texts), 1)
        text_row = texts[0]
        text_tds = text_row.find_elements_by_css_selector('td')
        if len(text_tds) == 1:
            self.wait_until_disappear(
                By.XPATH,
                '//td[contains(text(), "No matching records found")]')
        texts = self.finds(By.CSS_SELECTOR, '#text_table tbody tr')
        text_row = texts[0]
        text_tds = text_row.find_elements_by_css_selector('td')
        text_title = text_tds[5].text
        self.assertEqual(text_title, title_str)

        # creating a second text with tags:
        self.find(By.XPATH, '//a[@title="create a new text"]').click()
        select = Select(self.find(By.NAME, 'language'))
        select.select_by_visible_text(self.language_1.name)
        title2_str = 'another title'
        title = self.find(By.NAME, 'title')
        title.send_keys(title2_str)
        text = self.find(By.NAME, 'text')
        text.send_keys('And still another content for this text')
        wordtagarea = self.find(By.ID, 'id_texttags_tags_input_tag')
        wordtagarea.send_keys('testing')
        wordtagarea.send_keys(',')
        wordtagarea.send_keys('demo')
        wordtagarea.send_keys(',')
        save = self.find(By.ID, 'submit-id-save')
        save.click()

        self.selenium.get('{}/text_list/'.format(self.live_server_url))
        self.assertEqual(self.selenium.current_url,
                         '{}/text_list/'.format(self.live_server_url))
        #         self.find(By.CSS_SELECTOR, 'filterlangform input[value="1"]').click()
        self.find(By.CSS_SELECTOR, '#filterlangform input[value="2"]').click()
        self.wait_until_appear(By.XPATH,
                               '//td[contains(text(), "another title")]')
        texts = self.finds(By.CSS_SELECTOR, '#text_table tbody tr')
        if len(texts) == 1:
            self.wait_until_disappear(
                By.XPATH,
                '//td[contains(text(), "No matching records found")]')
        texts = self.finds(By.CSS_SELECTOR, '#text_table tbody tr')
        self.assertEqual(len(texts), 2)
        text_row = texts[1]
        text_tds = text_row.find_elements_by_css_selector('td')
        text_title = text_tds[4].text
        self.assertEqual(text_title, title2_str + ' [testing,demo]')


#     def test_create_wrong_text_symbol_content(self):
#         self.selenium.get('{}/text_detail/new/0/'.format(self.live_server_url))
#         select = Select(self.find(By.NAME,'language'))
#         select.select_by_visible_text('German')
#         title = self.find(By.NAME, 'title')
#         title.send_keys('An Example of Title')
#         text = self.find(By.NAME,'text')
#         text.send_keys('1245. 78')
#         save = self.find(By.NAME, 'save')
#         save.click()
#         text_field = self.find(By.ID, 'div_id_text')
#         tf_class = text_field.get_attribute('class')
#         assert ('has-error' in text_field.get_attribute('class'))
#         title_field = self.find(By.ID, 'div_id_title')
#         assert ('has-error' not in title_field.get_attribute('class'))
#
#     def test_create_wrong_text_blank_title(self):
#         self.selenium.get('{}/text_detail/new/0/'.format(self.live_server_url))
#         select = Select(self.find(By.NAME,'language'))
#         title = self.find(By.NAME, 'title')
#         title.send_keys('')
#         text = self.find(By.NAME,'text')
#         text.send_keys('An example of content')
#
#         save = self.find(By.NAME, 'save')
#         save.click()
#         text_field = self.find(By.ID, 'div_id_text')
#         assert ('has-error' not in text_field.get_attribute('class'))
#         title_field = self.find(By.ID, 'div_id_title')
#         assert ('has-error' in title_field.get_attribute('class'))
#
#     def test_create_wrong_text_blank_text(self):
#         self.selenium.get('{}/text_detail/new/0/'.format(self.live_server_url))
#         select = Select(self.find(By.NAME,'language'))
#         title = self.find(By.NAME, 'title')
#         title.send_keys('Example of title')
#         text = self.find(By.NAME,'text')
#         text.send_keys('')
#         save = self.find(By.NAME, 'save')
#         save.click()
#         text_field = self.find(By.ID, 'div_id_text')
#         assert ('has-error' in text_field.get_attribute('class'))
#         title_field = self.find(By.ID, 'div_id_title')
#         assert ('has-error' not in title_field.get_attribute('class'))
#
#     def test_upload_text_file(self):
#         self.selenium.get('{}/text_detail/?new=0/'.format(self.live_server_url))
#         myfile = open('Example_of_file_upload_title.txt', 'w+')
#         myfile.write('Example of content of file')
#         myfile.close()
#         myfile_path = os.path.join(os.getcwd(),'Example_of_file_upload_title.txt')
#         element = self.find(By.NAME, 'uploaded_text')
#         element.send_keys(myfile_path)
#         os.remove(myfile_path)
#         self.find(By.ID, 'submit-id-uploaded_text').click()
#
#         self.wait_until(By.ID, 'text_table')
# #         wait = WebDriverWait(self.selenium, 10)
# #         wait.until(EC.presence_of_element_located(By.ID, 'text_table'))
# #         self.selenium.implicitly_wait(10)
# #         self.wait_until(By.ID, 'text_table')
#         self.selenium.get('{}/text_list/'.format(self.live_server_url))
#         self.assertEqual(self.selenium.current_url, '{}/text_list/'.format(self.live_server_url))
#
# class Text_detail_no_js(BasePage_no_js):
#
#     @classmethod
#     def setUpClass(cls):
#         super(Text_detail_no_js, cls).setUpClass()
#         cls.language_1 = GermanLanguagesFactory(owner=cls.user_1)
#         Settings_currentlang_idFactory(owner=cls.user_1, stvalue=cls.language_1.id)
#         cls.selenium.get('{}/accounts/login/'.format(cls.live_server_url))
#         cls.selenium.implicitly_wait(10)
#         login = cls.selenium.find_element_by_name('login')
#         login.send_keys(cls.user_1.username)
#         pw = cls.selenium.find_element_by_name('password')
#         pw.send_keys(cls.pwd)
#         cls.selenium.find_element_by_class_name('primaryAction').click()
#
#     def test_create_wrong_text_symbol_content_no_js(self):
#         self.selenium.get('{}/text_detail/new/0/'.format(self.live_server_url))
#         select = Select(self.find(By.NAME,'language'))
#         select.select_by_visible_text('German')
#         title = self.find(By.NAME, 'title')
#         title.send_keys('An Example of Title')
#         text = self.find(By.NAME,'text')
#         text.send_keys('1245. 78')
#         save = self.find(By.NAME, 'save')
#         save.click()
#         text_field = self.find(By.ID, 'div_id_text')
#         tf_class = text_field.get_attribute('class')
#         assert ('has-error' in text_field.get_attribute('class'))
#         title_field = self.find(By.ID, 'div_id_title')
#         assert ('has-error' not in title_field.get_attribute('class'))
Exemplo n.º 42
0
def main():
    # preliminary settings
    # Using Firefox to access web
    options = Options()
    options.headless = True
    driver = webdriver.Firefox(
        options=options,
        executable_path=r'/usr/local/Cellar/geckodriver/0.26.0/bin/geckodriver'
    )
    print("Headless Firefox Initialized")

    # Open the website
    driver.get('https://www.lehrbetrieb.ethz.ch/laborpraktika/uebersicht.view')

    # find and click button
    driver.find_elements_by_xpath(
        "//input[@class='submit' and @value='Start']")[0].click()

    # Log in
    sleep(4)
    username = driver.find_element_by_id("username")
    password = driver.find_element_by_id("password")

    username.send_keys(credentials.username)
    password.send_keys(credentials.password)
    driver.find_element_by_xpath(
        "/html/body/section/div[2]/div[1]/div/div/div[4]/form/fieldset/div[4]/div[1]/div/button"
    ).click()

    # go to next page
    sleep(2)
    driver.find_element_by_xpath(
        "/html/body/div[3]/section/section[2]/div/div/div/a").click()

    # edit filter
    sleep(1)
    driver.find_element_by_xpath(
        "/html/body/div[3]/section/section[1]/div[2]/div/form[1]/h3").click()
    sleep(1)
    select_element = Select(
        driver.find_element_by_xpath("//*[@id='departmentId']"))
    select_element.select_by_visible_text("D-MAVT")
    driver.find_elements_by_xpath("//*[@id='freePlaces1']")[0].click()
    driver.find_elements_by_xpath("//*[@id='applyFilters']")[0].click()
    driver.minimize_window()

    # Scrape page for Labs
    while True:
        currenttime = strftime("%H:%M:%S", gmtime())
        if check_exists_by_xpath(driver, "//*[@class='praktikumHeader']"):
            labs = driver.find_elements_by_xpath(
                "//*[@class='praktikumHeader']")
            labs_list = ["Available labs:"]
            for lab in labs:
                head, sep, tail = lab.text.partition("anmeldbar")
                labs_list.append(head)

            labs_string = '\n'.join(labs_list)
            print(currenttime, "labs available. sending messages")

            for chat in credentials.chat_ids:
                labbot_telegram.telegram_send(labs_string, chat,
                                              credentials.token)

        else:
            print(currenttime, "No labs available")

        sleep(5 * 60)
        driver.refresh()
Exemplo n.º 43
0
def auto_purchase(driver, data, url):
    loginAcc = data["loginAcc"]
    loginPwd = data["loginPwd"]
    BuyerName = data["BuyerName"]
    BuyerMobile = data["BuyerMobile"]
    CardNum_single = data["CardNum_single"]
    multi_ThruMonth = data["multi_ThruMonth"]
    multi_ThruYear = data["multi_ThruYear"]
    multi_CVV2Num = data["multi_CVV2Num"]
    BuyerAddrCity = data["BuyerAddrCity"]
    BuyerAddrRegion = data["BuyerAddrRegion"]
    BuyerAddr = data["BuyerAddr"]

    #try:
    driver.get(url)

    # login
    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "loginAcc"))
    )
    email_element = driver.find_element_by_id("loginAcc")
    email_element.clear()
    email_element.send_keys(loginAcc)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "loginPwd"))
    )
    password_element = driver.find_element_by_id("loginPwd")
    password_element.clear()
    password_element.send_keys(loginPwd)
    time.sleep(5)
    button = driver.find_element_by_id("btnLogin")
    driver.execute_script("arguments[0].click();", button)

    # put into cart
    WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//li[@id='ButtonContainer']/button"))
    )
    driver.find_element_by_xpath("//li[@id='ButtonContainer']/button").click()

    # go to cart
    WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.ID, "ico_cart"))
    )
    driver.find_element_by_id('ico_cart').click()

    # go to payment
    WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//li[@class='CC']/a[@class='ui-btn']"))
    )
    button = driver.find_element_by_xpath("//li[@class='CC']/a[@class='ui-btn']")
    driver.execute_script("arguments[0].click();", button)

    # fill the form
    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@id='BuyerName']"))
    )
    elem = driver.find_element_by_xpath("//input[@id='BuyerName']")
    elem.clear()
    elem.send_keys(BuyerName)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@name='BuyerMobile']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='BuyerMobile']")
    elem.clear()
    elem.send_keys(BuyerMobile)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@name='CardNum_single']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='CardNum_single']")
    elem.clear()
    elem.send_keys(CardNum_single)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "multi_ThruMonth"))
    )
    select = Select(driver.find_element_by_id("multi_ThruMonth"))
    select.select_by_value(multi_ThruMonth)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "multi_ThruYear"))
    )
    select = Select(driver.find_element_by_id("multi_ThruYear"))
    select.select_by_value(multi_ThruYear)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@name='multi_CVV2Num']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='multi_CVV2Num']")
    elem.clear()
    elem.send_keys(multi_CVV2Num)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "BuyerAddrCity"))
    )
    select = Select(driver.find_element_by_id("BuyerAddrCity"))
    select.select_by_visible_text(BuyerAddrCity)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "BuyerAddrRegion"))
    )
    select = Select(driver.find_element_by_id("BuyerAddrRegion"))
    select.select_by_visible_text(BuyerAddrRegion)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@name='BuyerAddr']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='BuyerAddr']")
    elem.clear()
    elem.send_keys(BuyerAddr)

    ReceiverName = BuyerName
    ReceiverMobile = BuyerMobile 
    ReceiverAddrCity = BuyerAddrCity
    ReceiverAddrRegion = BuyerAddrRegion
    ReceiverAddr = BuyerAddr 

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@id='ReceiverName']"))
    )
    elem = driver.find_element_by_xpath("//input[@id='ReceiverName']")
    elem.clear()
    elem.send_keys(ReceiverName)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@name='ReceiverMobile']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='ReceiverMobile']")
    elem.clear()
    elem.send_keys(ReceiverMobile)  

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "ReceiverAddrCity"))
    )
    select = Select(driver.find_element_by_id("ReceiverAddrCity"))
    select.select_by_visible_text(ReceiverAddrCity)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.ID, "ReceiverAddrRegion"))
    )
    select = Select(driver.find_element_by_id("ReceiverAddrRegion"))
    select.select_by_visible_text(ReceiverAddrRegion)

    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//input[@name='ReceiverAddr']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='ReceiverAddr']")
    elem.clear()
    elem.send_keys(ReceiverAddr)

    # click to agree
    WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//input[@name='chk_agree']"))
    )
    elem = driver.find_element_by_xpath("//input[@name='chk_agree']")
    if elem.is_selected() == False:
        elem.click()
Exemplo n.º 44
0
def bookTKB():
    logging.warning('[TKB booking...]')

    options = Options()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.binary_location = GOOGLE_CHROME_BIN

    driver = webdriver.Chrome(executable_path=DRIVERLOCATION,
                              chrome_options=options)  # 選擇Chrome瀏覽器
    driver.set_window_size(400, 1800)

    ### get config
    config = getConfig()
    print(config)

    st = time.time()
    logging.warning('=== start {} ==='.format(st - st))
    driver.get(LOGIN_URL)
    connect_time = time.time()
    logging.warning('=== connected {} ==='.format(connect_time - st))

    islogin = checkInLogin(driver)
    if not islogin:
        logging.warning('fail to login')
        return False

    driver.find_element_by_id('id').click()
    driver.find_element_by_id('id').send_keys(USERID)
    driver.find_element_by_id('pwd').click()
    driver.find_element_by_id('pwd').send_keys(PASSWORD)
    driver.find_element_by_link_text('送出').click()

    get_submit_alert, sleep_times = False, 0
    while (not get_submit_alert):
        if sleep_times >= SLEEP_TIME:
            logging.warning('no alert in login')
            return False
        sleep_times += 1
        try:
            alogin = driver.switch_to_alert()
            print(alogin.text)
            alogin.accept()
            get_submit_alert = True
        except NoAlertPresentException:
            time.sleep(1)
            pass

    inCoursePage = checkInPage(driver)
    if not inCoursePage:
        logging.warning('fail to in course page')
        return False

    logging.warning('=== into_time ===')
    today = datetime.datetime.now()
    if today < datetime.datetime(today.year, today.month, today.day, 12 - 8, 0,
                                 0):
        # morning, booking noon
        rest_time = (datetime.datetime(today.year, today.month, today.day, 12 -
                                       8, 0, 0) - today).total_seconds() + 1
    else:
        # afternoon, booking midnight
        rest_time = (datetime.datetime(today.year, today.month, today.day, 23 -
                                       8, 59, 59) - today).total_seconds() + 2

    if rest_time > REST_THRESHOLD or rest_time < 0:
        logging.warning('something wrong on rest')
        return False

    #driver.save_screenshot('login.png')

    logging.warning('[sleeping {} minutes...]'.format(rest_time / 60))
    time.sleep(rest_time)
    logging.warning('[wake up and clean refresh course...]')

    ### push clear
    driver.find_element_by_link_text('清除').click()

    clearCoursePage = checkInPage(driver)
    if not clearCoursePage:
        logging.warning('fail to clear course page')
        return False

    #driver.save_screenshot('clear.png')

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    select_course = driver.find_element_by_css_selector(
        "select[id='class_selector']")
    options_course = Select(select_course)
    course_name = getCourse(config["course"], options_course)
    if not course_name:
        return False
    options_course.select_by_visible_text(course_name)
    logging.warning(course_name)

    select_date = driver.find_element_by_css_selector(
        "select[id='date_selector']")
    options_date = Select(select_date)
    date_name = getDate(config["date"], options_date)
    if not date_name:
        return False
    options_date.select_by_visible_text(date_name)
    logging.warning(date_name)

    select_branch = driver.find_element_by_css_selector(
        "select[id='branch_selector']")
    options_branch = Select(select_branch)
    position_name = getPostion(config["position"], options_branch)
    if not position_name:
        return False
    options_branch.select_by_visible_text(position_name)
    logging.warning(position_name)

    has_class = driver.find_elements_by_css_selector(
        'input[type=checkbox][value=hasClass]')

    if len(has_class) != 0:
        logging.warning('You already have seat')
        return False

    all_checkboxs = driver.find_elements_by_css_selector(
        'input[type=checkbox]')
    disabled_checkboxs = driver.find_elements_by_css_selector(
        'input[type=checkbox][disabled]')
    abled_checkboxs = [a for a in all_checkboxs if a not in disabled_checkboxs]

    checked = False
    for idx, checkbox in enumerate(all_checkboxs):
        if idx + 1 == 3:
            continue
        if checkbox in abled_checkboxs:
            checkbox.click()
            checked = True
            break

    #driver.save_screenshot('test.png')

    if not checked:
        logging.warning('no more session')
        return False

    ed = time.time()
    logging.warning('=== end {} ==='.format(ed - st))
    driver.find_element_by_link_text('送出').click()

    ### Todo: sleep and wait for the alert
    get_submit_alert, sleep_times = False, 0
    while (not get_submit_alert):
        if sleep_times >= SLEEP_TIME:
            print('fail to confirm submit')
            return False
        sleep_times += 1
        try:
            abook = driver.switch_to_alert()
            print(abook.text)
            abook.accept()
            get_submit_alert = True
        except NoAlertPresentException:
            time.sleep(1)
            pass

    get_submit_alert, final_sleep_times = False, 0
    while (not get_submit_alert):
        if (final_sleep_times >= SLEEP_TIME):
            print('No final alert')
            return False
        final_sleep_times += 1
        try:
            afinal = driver.switch_to_alert()
            print(afinal.text)
            afinal.accept()
            get_submit_alert = True
        except NoAlertPresentException:
            time.sleep(1)
            pass

    ### Todo: try 5 times until succeed with function call
    ### Todo: scheduling and get config each trial
    ### Todo: put the root directory of program into config
    return True
Exemplo n.º 45
0
Arquivo: tc1.py Projeto: haropy/python
# 页面操作
# 填充表单
from selenium import webdriver

driver = webdriver.Chrome()
element = driver.find_element_by_xpath("//select[@name='name']")
all_options = element.find_element_by_tag_name("option")
for option in all_options:
    print ("Value is:%s" % option.get_attribute("value"))
    option.click()
# select方法
from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_name('name'))
select.select_by_index("index")
select.select_by_visible_text("text")
select.select_by_value("value")

select.deselect_all()  # 取消所有选择
select.all_selected_options  # 获取所有已选项
select.options  # 获取所有可选选项

# 元素拖拽
element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")

from selenium.webdriver import ActionChains

action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()
Exemplo n.º 46
0
driver.find_element_by_xpath(
    "/html/body/app-root/app-home/div[1]/app-header/p-dialog[2]/div/div[2]/div/form/div[2]/button"
).click()

driver.find_element_by_xpath("//*[@id='userName']").send_keys("RaghavK91")

driver.find_element_by_xpath("//*[@id='usrPwd']").send_keys("June@@2020")

driver.find_element_by_xpath("//*[@id='cnfUsrPwd']").send_keys("June@@2020")

# Working with Dropdown
element = driver.find_element_by_xpath(
    "//*[@id='divMain']/div/app-user-registration/div[2]/div/div[2]/div[5]/form/div[4]/div[2]/p-dropdown/div/label"
)
drp = Select(element)
drp.select_by_visible_text('What was the name of your first school')

#Working with the radio buttons
status = driver.find_element_by_id("M").click()
status = driver.find_element_by_id("M").is_selected()  #gives True or False
print(status)
driver.find_element_by_xpath(
    "//*[@id='divMain']/div/app-user-registration/div[2]/div/div[2]/div[5]/form/div[10]/div[2]/label[2]/input"
).click()

# Working with checkboxes
driver.find_element_by_id("sbi").click()  #Info about IRCTC SBI card
driver.find_element_by_xpath(
    "//*[@id='divMain']/div/app-user-registration/div[2]/div/div[2]/div[5]/form/div[21]/div/input"
).click()  #Terms and Conditions check box
Exemplo n.º 47
0
def search_stimmrechtsmitteilungen(start_date=None,
                                   end_date=None,
                                   results_per_page=4):
    """
    Performs a search for given parameters to initiate a session
    in Unternehmensregister.
    Returns a driver and full result URL with sessionID
    """
    # Set parameters for search
    publication_category = "Stimm­rechts­mitteilungen"
    publication_type = "Mitteilung bedeutender Stimm­rechts­anteile"
    language = "Deutsch"
    if start_date == None:
        start_date = "01.01.2007"
    if end_date == None:
        end_date = date.today().strftime("%d.%m.%Y")
    """
    @var: results_per_page
        0 ==> 10
        1 ==> 20
        2 ==> 30
        3 ==> 50
        4 ==> 100
    """
    results_per_page = results_per_page

    # Start search with given parameters
    chromedriver_path = os.path.join(os.getcwd(), "chromedriver")
    driver = webdriver.Chrome(chromedriver_path)
    driver.get("https://unternehmensregister.de")
    main_menu_toggle = driver.find_element_by_class_name("menu__toggle")
    main_menu_toggle.click()
    search_menu_toggle = driver.find_element_by_class_name("menu_headline")
    search_menu_toggle.click()
    capital_market_search_button = driver.find_element_by_partial_link_text(
        "Kapitalmarkt")
    capital_market_search_button.click()

    publication_category_input = Select(
        driver.find_element_by_id(
            "searchRegisterForm:publicationsOfCapitalInvestmentsCategory"))
    publication_category_input.select_by_visible_text(publication_category)

    publication_type_input = Select(
        driver.find_element_by_id(
            "searchRegisterForm:publicationsOfCapitalInvestmentsPublicationType"
        ))
    publication_type_input.select_by_visible_text(publication_type)

    language_input = Select(
        driver.find_element_by_id(
            "searchRegisterForm:publicationsOfCapitalInvestmentsLanguage"))
    language_input.select_by_visible_text(language)

    start_date_input = driver.find_element_by_id(
        "searchRegisterForm:publicationsOfCapitalInvestmentsPublicationsStartDate"
    )
    end_date_input = driver.find_element_by_id(
        "searchRegisterForm:publicationsOfCapitalInvestmentsPublicationsEndDate"
    )
    start_date_input.clear()
    end_date_input.clear()
    start_date_input.send_keys(start_date)
    end_date_input.send_keys(end_date)

    driver.find_element_by_name("searchRegisterForm:j_idt267").click()

    # adjust results per page
    results_per_page_input = Select(
        driver.find_element_by_id("hppForm:hitsperpage"))
    results_per_page_input.select_by_index(results_per_page)
    result_url = driver.current_url

    return driver, result_url
    select = Select(driver.find_element_by_id('SUBJECTCODE'))
    sleep(1)
    if row["Subject"] == "Networking":
        select.select_by_index(4)
    else:
        select.select_by_index(5)

    driver.find_element(By.XPATH, '//textarea[@id="topic_covered"]').send_keys(
        row["Topic Covered"])
    driver.find_element(By.XPATH, '//textarea[@id="platform_used"]').send_keys(
        row["Platform Used"])

    select = Select(driver.find_element_by_id('class_taken_by'))
    sleep(1)
    select.select_by_visible_text(teachers[row["Class Taken By"]])

    driver.execute_script(
        'document.getElementById("date_tme").removeAttribute("readonly")')
    driver.execute_script(
        'var aa=document.getElementsByClassName("datetimepicker datetimepicker-dropdown-bottom-right dropdown-menu")[0];aa.parentNode.removeChild(aa)'
    )
    driver.find_element(By.XPATH,
                        '//input[@id="date_tme"]').send_keys(row["Date/Time"])

    # have format: "24.04.2020,10AM" expected: "2020-05-16 22:55"

    driver.find_element(By.XPATH,
                        '//input[@id="record_lecture_upload_link"]').send_keys(
                            row["Record Lecture Upload Link"])
    driver.find_element(By.XPATH, '//input[@id="duration_in_min"]').send_keys(
Exemplo n.º 49
0
driver.get("https://kyfw.12306.cn/otn/leftTicket/init")

# 输入起始站点
fromEle = driver.find_element_by_id('fromStationText')
fromEle.click()
fromEle.clear()
fromEle.send_keys(u'南京\n')

toEle = driver.find_element_by_id('toStationText')
toEle.click()
toEle.clear()
toEle.send_keys(u'镇江\n')

timeSelect = Select(driver.find_element_by_id('cc_start_time'))
timeSelect.select_by_visible_text('06:00--12:00')

tomorrow = driver.find_element_by_css_selector('#date_range li:nth-child(3)')

i=0
while True:
    i += 1
    isGet = False  # 设置为没有找到
    tomorrow.click()
    # 选择二等座有票的车
    xpath = '//*[@id="queryLeftTable"]//td[4][@class]/../td[1]//a'
    interested = ['G7035', 'G7039', 'G1377', 'G7355']
    theTrains = driver.find_elements_by_xpath(xpath)

    for one in theTrains:
        name = one.text
Exemplo n.º 50
0
time.sleep(2)

tab2 = driver.find_element_by_class_name(
    'main-menu-nav.player-center-navigation')
tab2.find_element_by_id('menu_security').click()
driver.execute_script("window.scrollTo(0,700)")
time.sleep(2)
driver.execute_script("window.scrollTo(700,0)")
time.sleep(1)

tab3 = driver.find_element_by_class_name(
    'main-menu-nav.player-center-navigation')
tab3.find_element_by_id('menu_account_history').click()
accounthist = Select(driver.find_element_by_id('pageLength'))
time.sleep(2)
accounthist.select_by_visible_text('100')
time.sleep(1)
date = driver.find_element_by_id("cdate")
elem = driver.find_element_by_class_name("fm-ul.nav.nav-pills.nav-justified")
element2 = elem.find_elements_by_tag_name("li")[0].click()
date.clear()
date.send_keys("2019-06-01 00:00:00 To 2019-06-24 23:59:59")
time.sleep(1)
date = driver.find_element_by_id("search_btn").click()
time.sleep(1)
try:
    a = driver.find_element_by_id('rebateResultTable')
    element = a.find_element_by_class_name('dataTables_empty')
    if element.is_displayed():
        print("Cashback History: No data available in table")
except NoSuchElementException:
Exemplo n.º 51
0
 def changeNumberOfChild(self, number_of_child):
     select = Select(
         self.driver.find_element_by_xpath(CHILD_SELECTOR_XPATH))
     select.select_by_visible_text(str(number_of_child) + "人")
Exemplo n.º 52
0
# 执行鼠标操作
ac.perform()

loc = By.XPATH, '//a[text()="高级搜索"]'
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
driver.find_element(*loc).click()

# select类 下拉框操作
# selenium 提供了Select类来处理select/option
# 引入类 from selenium.webdriver.support.ui import Select

# 选择下拉列表值的三种方法
# 1.通过下标选择,select_by_index(index值) 从0开始
# 2.通过value属性:select_by_value(value值)
# 3.通过文本内容:select_by_visible_text(文本内容)

# 先找到select元素
loc = By.XPATH, '//select[@name="ft"]'
WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc))
select_ele = driver.find_element(*loc)

# 实例化Select类
s = Select(select_ele)
s.select_by_index(4)
time.sleep(3)
s.select_by_value('all')
time.sleep(3)
s.select_by_visible_text('Adobe Acrobat PDF (.pdf)')
time.sleep(3)
driver.quit()
Exemplo n.º 53
0
    def test_add_food(self):

        self.initialize_test(self.USERNAME, self.PASSWORD)

        # Joe has some potato chips that he would like to the DB
        # so he goes to the 'Add Food' tabe.
        self.browser.find_element_by_id("add-food-tab").click()

        # Once he arrives he sees a form with inputs for adding a new food
        name_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-name"]')[0].text
        self.assertEqual(name_label, "Food Name")

        name_input = ["input[id='add-food-name']"]
        name_input_value = ["Potato Chips"]
        self.fill_input(name_input, name_input_value)

        serving_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-grams"]')[0].text
        serving_input = self.browser.find_element_by_id("add-food-grams")

        select_option = self.browser.find_elements_by_css_selector(
            'input[type="checkbox"]')[0]
        serving_desc = self.browser.find_element_by_id("add-food-unit-desc")
        serving_qnty = self.browser.find_element_by_id(
            "add-food-unit-quantity")

        self.assertFalse(serving_desc.is_enabled())
        self.assertFalse(serving_qnty.is_enabled())
        select_option.click()
        self.assertTrue(serving_desc.is_enabled())
        self.assertTrue(serving_qnty.is_enabled())

        self.assertEqual(serving_label, "Servings (grams)")
        serving_input.send_keys("100")

        unit_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-unit-desc"]')[0].text
        unit_input = self.browser.find_element_by_id("add-food-unit-desc")
        self.assertEqual(unit_label,
                         "Servings Unit (ex. cups, tsp, package, etc.)")
        unit_input.send_keys("cup")

        unit_amt_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-unit-quantity"]')[0].text
        unit_amt_input = self.browser.find_element_by_id(
            "add-food-unit-quantity")
        self.assertEqual(unit_amt_label, "Unit Quantity")
        unit_amt_input.send_keys("2")

        cals_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-cals"]')[0].text
        cals_input = self.browser.find_element_by_id("add-food-cals")
        self.assertEqual(cals_label, "Cals")
        cals_input.send_keys("536")

        fat_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-fat"]')[0].text
        fat_input = self.browser.find_element_by_id("add-food-fat")
        self.assertEqual(fat_label, "Fat")
        fat_input.send_keys("35")

        carbs_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-carbs"]')[0].text
        carbs_input = self.browser.find_element_by_id("add-food-carbs")
        self.assertEqual(carbs_label, "Carbs")
        carbs_input.send_keys("53")

        sugar_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-sugar"]')[0].text
        sugar_input = self.browser.find_element_by_id("add-food-sugar")
        self.assertEqual(sugar_label, "Sugar")
        sugar_input.send_keys("0.2")

        protein_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-protein"]')[0].text
        protein_input = self.browser.find_element_by_id("add-food-protein")
        self.assertEqual(protein_label, "Protein")
        protein_input.send_keys("7")

        food_group_label = self.browser.find_elements_by_css_selector(
            'label[for="add-food-food-group"]')[0].text
        food_group_select = Select(
            self.browser.find_element_by_id("add-food-food-group"))
        self.assertEqual(food_group_label, "Food Group")
        food_group_select.select_by_visible_text("Snacks")

        save_button = self.browser.find_element_by_id("add-food-save")
        self.assertEqual(save_button.text, "Save New Food")
        # Joe enters all the info in the form and clicks the 'Add Food to DB'
        # button after which he sees a 'New Food Successfully Added' message.

        save_button.click()

        status = self.browser.find_element_by_id("add-food-save-status")
        self.assertEqual(status.text, "Food Saved!")
        time.sleep(4)  # wait for status to dissapear
        self.assertEqual(status.text, "")

        # He notices the form has been cleared.

        # He then enters a new food without the serving info and notices that it
        # still saves

        self.fill_input(name_input, [], clear=True)
        name_input_value = ["Sweet Potato Chips"]
        self.fill_input(name_input, name_input_value)

        self.fill_input(['input[id="add-food-unit-desc"]'], [], clear=True)
        self.fill_input(['input[id="add-food-unit-quantity"]'], [], clear=True)

        select_option.click()
        save_button.click()

        self.assertEqual(status.text, "Food Saved!")
        time.sleep(4)  # wait for status to dissapear
        self.assertEqual(status.text, "")
Exemplo n.º 54
0
driver.implicitly_wait(8)
# Open the Gorentals' main page
driver.get(constants.GORENTALS_BOOKING_PAGE_URL)

driver.find_element_by_id("locationPickerStart").click()
elements = driver.find_elements_by_css_selector(
    "div.multiselect__tags > span.multiselect__single")
for element in elements:
    result = element.text
    print(result)

# Click the Pick-up button and select one pick_up_location in the dropbox
driver.find_element_by_id("locationPickerStart").click()
time.sleep(5)
pick_up_location = Select(driver.find_element_by_id("locationPickerStart"))
pick_up_location.select_by_visible_text("Auckland City")

# Click the drop-off button and select one drop_off_location in the dropbox
driver.find_element_by_id("locationPickerEnd").click()
drop_off_location = Select(driver.find_element_by_id("locationPickerEnd"))
drop_off_location.select_by_visible_text("Christchurch Airport")

# select one pick_up_date in the calendar
driver.find_element_by_id("datePickerStart").click()
element1 = driver.find_element_by_css_selector(
    "#__layout > div > div.flex-1-0-auto > main > header > content > div.position-absolute.top.left.width-span12.height-span12.tablet\:paddingRight-48.desktop\:paddingRight-56 > div > div.flex-1.display-flex.flexDirection-column.justifyContent-flexEnd.paddingTop-16.paddingBottom-16.tablet\:justifyContent-center.tablet\:paddingBottom-8.tabletWide\:paddingBottom-32 > div > div > form > div:nth-child(1) > p.gridColumn-span7 > span > div > div > div.c-header > div:nth-child(3) > svg > path"
)
webdriver.ActionChains(driver).move_to_element(element1).click(
    element1).perform()
time.sleep(2)
webdriver.Chrome().refresh
Exemplo n.º 55
0
    def fillout(self):
        """
        お届け先・支払い情報の入力
        """

        # 名前
        locator = CheckoutPageLocator.name
        name = WebDriverWait(self.driver,
                             60).until(EC.element_to_be_clickable(locator))
        name.send_keys(CHECKOUT_INFO['name'])

        sleep(FILL_OUT_DELAY)

        # Eメール
        locator = CheckoutPageLocator.email
        email = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        email.send_keys(CHECKOUT_INFO['email'])

        sleep(FILL_OUT_DELAY)

        # 電話番号
        locator = CheckoutPageLocator.phone_number
        phone_number = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        phone_number.send_keys(CHECKOUT_INFO['phone_number'])

        sleep(FILL_OUT_DELAY)

        # 郵便番号
        locator = CheckoutPageLocator.zip_code
        zip_code = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        zip_code.send_keys(CHECKOUT_INFO['zip_code'])

        sleep(FILL_OUT_DELAY)

        # 都道府県
        locator = CheckoutPageLocator.billing_state
        billing_state = Select(
            WebDriverWait(self.driver,
                          60).until(EC.presence_of_element_located(locator)))
        billing_state.select_by_visible_text(CHECKOUT_INFO['billing_state'])

        sleep(FILL_OUT_DELAY)

        # 区市町村
        locator = CheckoutPageLocator.billing_city
        billing_city = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        billing_city.clear()
        billing_city.send_keys(CHECKOUT_INFO['billing_city'])

        sleep(FILL_OUT_DELAY)

        # 住所
        locator = CheckoutPageLocator.billing_address
        billing_address = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        billing_address.send_keys(CHECKOUT_INFO['billing_address'])

        sleep(FILL_OUT_DELAY)

        # この住所を保存する
        locator = CheckoutPageLocator.store_address_check_box
        store_address_check_box = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        store_address_check_box.click()

        sleep(FILL_OUT_DELAY)

        # 支払い方法
        locator = CheckoutPageLocator.card_type_select_box
        card_type = Select(
            WebDriverWait(self.driver,
                          60).until(EC.presence_of_element_located(locator)))
        card_type.select_by_visible_text(CHECKOUT_INFO['card_type'])

        sleep(FILL_OUT_DELAY)

        # カード番号
        locator = CheckoutPageLocator.card_number
        card_number = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        card_number.send_keys(CHECKOUT_INFO['card_number'])

        sleep(FILL_OUT_DELAY)

        # 有効期限(月)
        locator = CheckoutPageLocator.card_month_select_box
        card_month_select_box = Select(
            WebDriverWait(self.driver,
                          60).until(EC.presence_of_element_located(locator)))
        card_month_select_box.select_by_value(CHECKOUT_INFO['card_month'])

        sleep(FILL_OUT_DELAY)

        # 有効期限(年)
        locator = CheckoutPageLocator.card_year_select_box
        card_year_select_box = Select(
            WebDriverWait(self.driver,
                          60).until(EC.presence_of_element_located(locator)))
        card_year_select_box.select_by_value(CHECKOUT_INFO['card_year'])

        sleep(FILL_OUT_DELAY)

        # CSV番号
        locator = CheckoutPageLocator.card_cvv
        card_cvv = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        card_cvv.send_keys(CHECKOUT_INFO['card_cvv'])

        sleep(FILL_OUT_DELAY)

        # 利用規約同意
        locator = CheckoutPageLocator.agreement_check_box
        agreement_check_box = WebDriverWait(self.driver, 60).until(
            EC.presence_of_element_located(locator))
        agreement_check_box.click()

        sleep(FILL_OUT_DELAY)
Exemplo n.º 56
0
 def changeNumberOfAdult(self, number_of_adult):
     select = Select(
         self.driver.find_element_by_xpath(ADULT_SELECTOR_XPATH))
     select.select_by_visible_text(str(number_of_adult) + "人")
Exemplo n.º 57
0
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time


def sum(x, y):
    return str(int(x) + int(y))


try:
    link1 = "http://suninjuly.github.io/selects1.html"
    link2 = "http://suninjuly.github.io/selects2.html"
    browser = webdriver.Chrome()
    browser.get(link1)

    num1 = browser.find_element_by_id("num1")
    x = num1.text
    num2 = browser.find_element_by_id("num2")
    y = num2.text
    select = Select(browser.find_element_by_tag_name("select"))
    select.select_by_visible_text(sum(x, y))

    submit = browser.find_element_by_css_selector("button.btn")
    submit.click()

finally:
    time.sleep(10)
    browser.quit()
Exemplo n.º 58
0
 def find_select_element_by_id(self, _id, workflowName, waitFor=WAITFOR):
     selected = self.driver.find_element_by_id(_id)
     select = Select(selected)
     select.select_by_visible_text(workflowName)
def step_impl(context, text):
    time.sleep(2)

    #Select guitar submodel
    guitar_submodel = context.driver.find_element_by_xpath(
        "//a[contains(@title, '" + text + "')]")
    guitar_submodel.click()

    time.sleep(2)

    #Add Guitar to cart
    add_to_cart_button = context.driver.find_element_by_xpath(
        "//button[@title='Add to Cart']")
    add_to_cart_button.click()

    time.sleep(4)

    # View the shopping cart  (see if we can get an independent action to hoover over view cart)

    view_cart_button = context.driver.find_element_by_xpath(
        "//*[@id='mini-cart']/div[2]/div[4]/a")
    time.sleep(1)
    view_cart_button.click()

    #context.driver.get('https://shop.fender.com/en-US/cart')

    #Click on secure check out

    time.sleep(2)

    sec_checkout_button = context.driver.find_elements_by_xpath(
        "//*[@id='checkout-form']/fieldset/button")[-1]
    sec_checkout_button.click()

    time.sleep(1)

    checkout_guest_button = context.driver.find_elements_by_xpath(
        "//button[@value='Check Out as Guest']")[-1]
    checkout_guest_button.click()

    # Fill in customer information form

    time.sleep(2)

    input_first_name = context.driver.find_element_by_xpath(
        "//input[@id='dwfrm_singleshipping_shippingAddress_addressFields_firstName']"
    )
    time.sleep(2)
    input_first_name.send_keys('David')

    input_last_name = context.driver.find_element_by_xpath(
        "//input[@id='dwfrm_singleshipping_shippingAddress_addressFields_lastName']"
    )
    input_last_name.clear()
    input_last_name.send_keys('Palomar')

    input_address_1 = context.driver.find_element_by_xpath(
        "//input[@id='dwfrm_singleshipping_shippingAddress_addressFields_address1']"
    )
    input_address_1.clear()
    input_address_1.send_keys('329 North First Street')

    input_city = context.driver.find_element_by_xpath(
        "//input[@id='dwfrm_singleshipping_shippingAddress_addressFields_city']"
    )
    input_city.clear()
    input_city.send_keys('San Jose')

    select_state = Select(
        context.driver.find_element_by_xpath(
            "//*[@id='dwfrm_singleshipping_shippingAddress_addressFields_states_state']"
        ))
    select_state.select_by_visible_text("California")

    zip_code = context.driver.find_element_by_xpath(
        "//input[@id='dwfrm_singleshipping_shippingAddress_addressFields_zip']"
    )
    zip_code.clear()
    zip_code.send_keys('95110')

    phone = context.driver.find_element_by_xpath(
        "//*[@id='dwfrm_singleshipping_shippingAddress_addressFields_phone']")
    phone.clear()
    phone.send_keys('4083334446')

    continue_button = context.driver.find_elements_by_xpath(
        "//label[@value='Continue ']")[-1]
    continue_button.click()

    time.sleep(3)
Exemplo n.º 60
0
 def select_size(self, text):
     locator = ProductPageLocator.size_select_box
     wait = WebDriverWait(self.driver,
                          60).until(EC.presence_of_element_located(locator))
     size_select_box = Select(wait)
     size_select_box.select_by_visible_text(text)