Beispiel #1
0
 def test_can_create_meetup(self):
     self.make_admin()
     self.browser.get(self.live_server_url)
     self.browser.add_cookie(self.create_session_cookie())
     self.browser.refresh()
     self.browser.get('{}{}'.format(self.live_server_url, '/meetup/add/'))
     name = self.browser.find_element_by_id("id_name")
     slug = self.browser.find_element_by_id("id_slug")
     location = Select(self.browser.find_element_by_id("id_location"))
     email = self.browser.find_element_by_id("id_email")
     name.send_keys("Foo Community")
     slug.send_keys("foo-community")
     email.send_keys("*****@*****.**")
     location.select_by_index(1)
     # Locate the CKE iframe for description
     description = self.browser.find_element_by_xpath(
         "//div[contains(@id, 'cke_1_contents')]/iframe")
     self.browser.switch_to.frame(description)  # switch context to iframe
     description_editor = self.browser.find_element_by_xpath("//body")
     description_editor.send_keys("Foo description")
     self.browser.switch_to_default_content()  # return to main context
     # Locate the CKE iframe for sponsors
     sponsors = self.browser.find_element_by_xpath(
         "//div[contains(@id, 'cke_2_contents')]/iframe")
     self.browser.switch_to.frame(sponsors)
     sponsors_editor = self.browser.find_element_by_xpath("//body")
     sponsors_editor.send_keys("Foo sponsor")
     self.browser.switch_to_default_content()
     self.browser.find_element_by_id('submit-id-save').click()
     message = self.browser.find_element_by_class_name('container').text
     self.assertTrue('Meetup added Successfully' in message)
Beispiel #2
0
def main(webdriver):
    login(webdriver)
    submit_button = webdriver.find_element_by_class_name('Submit')
    submit_button.click()

    try:
        WebDriverWait(webdriver, int(os.environ.get('TIMEOUT'))).until(
            EC.presence_of_element_located((By.XPATH, "//*[contains(text(), 'Date of birth:')]"))
        )
    except TimeoutException as error:
        raise Exception('Timed out waiting for page to load')

    multi_driver_check = webdriver.find_elements_by_xpath("//*[contains(text(), 'Date of birth:')]")  # Array where len(check) will tell you how many vehicles in policy
    if len(multi_driver_check) >= 2:
        remove_driver_buttons = webdriver.find_elements_by_xpath('//button[text()="Remove"]')
        if remove_driver_buttons and len(remove_driver_buttons) >= 2:
            remove_driver_buttons[1].click()
        else:
            raise Exception('Could not find driver_remove button')
        webdriver.find_element_by_xpath('//a[@href="/account/drivers/01/remove"]').click()
        try:
            WebDriverWait(webdriver, int(os.environ.get('TIMEOUT', 5))).until(
                EC.presence_of_element_located((By.NAME, 'requester_name'))
            )
        except TimeoutException:
            raise Exception('Timed out waiting for requester_name_field')

        requester_name_field = Select(webdriver.find_element_by_name('requester_name'))
        requester_name_field.select_by_index(1)
        driver_remove_reason_field = Select(webdriver.find_element_by_name('driver_remove_reason'))
        driver_remove_reason_field.select_by_visible_text('No longer lives in the household')
        date_fields = webdriver.find_elements_by_name("date_input")
        date_fields[0].send_keys('{}'.format(datetime.date.today() + datetime.timedelta(days=2)))
        other_frequent_driver_field = Select(webdriver.find_element_by_name('other_frequent_driver'))
        other_frequent_driver_field.select_by_visible_text('None')
        vehicle_usage_field = Select(webdriver.find_element_by_name('vehicle_usage'))
        vehicle_usage_field.select_by_visible_text('Pleasure')
        vehicle_annual_kms_field = webdriver.find_element_by_name('vehicle_annual_kms')
        vehicle_annual_kms_field.send_keys('90')
        date_fields = webdriver.find_elements_by_name("date_input")
        date_fields[0].send_keys('{}'.format(datetime.date.today() + datetime.timedelta(days=2)))

        vehicle_usage_fields = webdriver.find_elements_by_xpath('//select[@name="vehicle_usage"]')
        annual_kms_fields = webdriver.find_elements_by_name('vehicle_annual_kms')
        if vehicle_usage_fields:
            for field in vehicle_usage_fields:
                select_vehicle_usage_field = Select(field)
                select_vehicle_usage_field.select_by_visible_text('Pleasure')
        if annual_kms_fields:
            for field in annual_kms_fields:
                field.send_keys('123')

        for num in range(1, len(multi_driver_check) + 1):
            stringified_num = '0{}'.format(num)
            x_principal_driver_field = webdriver.find_elements_by_xpath("//select[@name={0}]".format("'veh_{}_principal_driver'".format(stringified_num)))
            if x_principal_driver_field:
                Select(x_principal_driver_field[0]).select_by_index(1)
    else:
        raise Exception('Can only remove driver if policy has 2+ drivers')
        webdriver.close()
 def _select_text_download(self):
     """Select text format to download"
     
     Get dropdown element and select index/option 3 which corresponds to text
     """
     mySelect = Select(self.driver.find_element_by_css_selector('#delFmt'))
     mySelect.select_by_index(3)
def walkProd():
    global driver, prevTrail
    try:
        # click overlay advertisement popup left button "No Thanks"
        try:
            driver.find_element_by_css_selector("a.btn.close.fl-left").\
                    click()
        except (NoSuchElementException):
            pass

        zpath = ('#ctl00_ctl00_ctl00_mainContent_localizedContent_bodyCenter'+
                 '_adsPanel_lbProduct')
        waitTextChanged(zpath)
        curSel = Select(css(zpath))
        numProds = len(curSel.options)
        ulog("numProds=%d"%numProds)

        startIdx = getStartIdx()
        for idx in range(startIdx, numProds):
            curSel = Select(css(zpath))
            ulog("idx=%s"%idx)
            ulog('select "%s"'%curSel.options[idx].text)
            curSel.select_by_index(idx)
            prevTrail+=[idx]
            while True:
                ret = walkFile()
                if ret != TRY_AGAIN:
                    break
            if ret== PROC_GIVE_UP:
                ulog('"%s" is GIVE UP'% curSel.options[idx].text)
            prevTrail.pop()
        return PROC_OK
    except Exception as ex:
        traceback.print_exc(); ipdb.set_trace()
        driver.save_screenshot('netgear_exc.png')
Beispiel #5
0
 def backpack(self, item_name, pokemon=None, qty=None):
     img_xpath = "//img[@src='images/pokesklep/{0}.jpg' and contains(@class, 'box-center')]".format(item_name)
     # check if element is present, if not open backpack
     if not is_present(By.XPATH, img_xpath):
         self.menu_get(0, 2)  # opens backpack from menu
     # getting tab name
     item_img = driver.find_element_by_xpath(img_xpath)
     div = item_img.find_element_by_xpath(img_xpath+"/ancestor::div[@role='tabpanel']")
     tab_id = div.get_attribute('id')
     # opening backpack tab
     tab_xpath = "//a[@aria-controls='{0}']".format(tab_id)
     backpack_tab = driver.find_element_by_xpath(tab_xpath)
     backpack_tab.click()
     # waiting for tab to load and visibility of item
     item_button = wait_visible(item_img)
     item_button.click()
     # locating form to use item
     form_xpath = "//input[@value='{0}' and @name='rodzaj_przedmiotu']/parent::*".format(item_name)
     form = wait_visible(driver.find_element_by_xpath(form_xpath))
     # locating button to send form.
     # non default quantity of item to use
     if qty:
         qty_input = wait_visible(form.find_element_by_xpath("input[@name='ilosc']"))
         qty_input.send_keys(str(qty))
     # if pokemon is specified chosing him from select menu
     if pokemon:
         select = Select(form.find_element_by_tag_name('select'))
         select.select_by_index(pokemon-1)
     button = form.find_element_by_tag_name('button')
     button.click()
     load_page()
    def fill_form(self):
        # Fills out the form with the most basic answers right up to the point before submitting
        requester_name_field = Select(self.webdriver.find_element_by_name('requester_name'))
        self.webdriver.save_screenshot('screenshots/address_change_form/{0}-{1}.png'.format(datetime.datetime.now(), 'start')) if self.screenshots else False
        requester_name_field.select_by_index(1)
        postal_code_field = self.webdriver.find_element_by_name('postal_code')
        postal_code_field.send_keys('N9G 2Z4')
        postal_code_field.send_keys(Keys.TAB)
        new_street_number_field = self.webdriver.find_element_by_name('new_street_number')
        new_street_number_field.send_keys('111')
        effective_date_field = self.webdriver.find_element_by_name("date_input")
        effective_date_field.send_keys('{}'.format(datetime.date.today() + datetime.timedelta(days=2)))
        other_frequent_driver_field = Select(self.webdriver.find_element_by_name('other_frequent_driver'))
        other_frequent_driver_field.select_by_visible_text('None')
        vehicle_usage_field = Select(self.webdriver.find_element_by_xpath("//select[@name='vehicle_usage']"))
        vehicle_usage_field.select_by_visible_text("Pleasure")
        annual_kms_fields = self.webdriver.find_elements_by_name('vehicle_annual_kms')
        for index in range(len(self.multi_vehicle_check)):
            annual_kms_fields[index].send_keys('12345')
        self.webdriver.save_screenshot('screenshots/address_change_form/{0}-{1}.png'.format(datetime.datetime.now(), 'half_filled')) if self.screenshots else False
        veh_01_principal_driver_field = Select(self.webdriver.find_element_by_xpath("//select[@name='veh_01_principal_driver']"))
        veh_01_principal_driver_field.select_by_index(1)

        for num in range(2, len(self.multi_vehicle_check) + 1):
            #  fill in principal_driver field for 'x' vehicle
            stringified_num = '0{}'.format(num)
            x_principal_driver_field = self.webdriver.find_elements_by_xpath("//select[@name={0}]".format("'veh_{}_principal_driver'".format(stringified_num)))
            if x_principal_driver_field:
                Select(x_principal_driver_field[0]).select_by_index(1)
def test_add_meas_order_two_item(admin_client, live_server, webdriver):
    selenium = webdriver()
    selenium.implicitly_wait(3)
    try:
        create_correct_sample_data()
        num_orders_before = len(MeasurementOrder.objects.all())
        num_items_before = len(MeasurementItem.objects.all())
        selenium.get(live_server + '/new_item_and_order/')
        login_as_admin(selenium)
        order_type = Select(selenium.find_element_by_id('id_order_type'))
        order_type.select_by_index(1)
        selenium.find_element_by_class_name('add_meas_item_btn').click()
        serial_nrs = selenium.find_elements_by_id('id_serial_nr')
        names = selenium.find_elements_by_id('id_name')
        products = selenium.find_elements_by_id('id_product')
        index = 0
        for serial_nr, name, product, in zip(serial_nrs, names, products):
            name.send_keys('Teddy the bear')
            serial_nr.send_keys(str(4712 + index))
            Select(product).select_by_index(index % 3 + 1)
            index += 1
        selenium.find_element_by_name('action').click()
        wait_for_root_page(selenium)
        assert selenium.current_url == live_server.url + '/'
        assert len(MeasurementOrder.objects.all()) == num_orders_before + 1
        assert len(MeasurementItem.objects.all()) == num_items_before + 2
        assert MeasurementItem.objects.get(serial_nr=4712)
        assert MeasurementItem.objects.get(serial_nr=4713)
    finally:
        selenium.quit()
Beispiel #8
0
    def fill_form(self, **data):
        if not data:
            data = {
                'id_name': 'name',
                'id_surname': 'surname',
                'id_email': '*****@*****.**',
                'id_quantity': 1,
                'id_product': 1,
            }
        form = self.driver.find_element_by_css_selector(
                        'main > form')
        form_inputs = form.find_elements_by_css_selector(
                        'div .controls input')
        form_select = Select(form.find_element_by_css_selector(
                        'div .controls select'))
        for form_input in form_inputs:
            input_id = form_input.get_attribute('id')
            form_input.clear()
            form_input.send_keys(data[input_id])
            if self.SLOW_DOWN:
                time.sleep(1)

        form_select.select_by_index(data['id_product'])
        if self.SLOW_DOWN:
            time.sleep(1)
        form.submit()
Beispiel #9
0
 def select(self, target, value):
     """
     Select an option of a select box.
     @param target: a element locator pointing at a select element
     @param value: an option locator which points at an option of the select element
     Option locators can have the following formats:
     label=labelPattern: matches options based on their labels, i.e. the visible text. (This is the default.)
         example: "label=regexp:^[Oo]ther"
     value=valuePattern: matches options based on their values.
         example: "value=other"
     id=id: matches options based on their ids.
         example: "id=option1"
     index=index: matches an option based on its index (offset from zero).
         example: "index=2"
     """
     target_elem = self._find_target(target)
     tag, tvalue = self._tag_and_value(value)
     select = Select(target_elem)
     # the select command in the IDE does not execute javascript. So skip this command if javascript is executed
     # and wait for the following click command to execute the click event which will lead you to the next page
     if not target_elem.find_elements_by_css_selector('option[onclick]'):
         #import pdb; pdb.set_trace()
         if tag in ['label', None]:
             tvalue = self._matchOptionText(target_elem, tvalue)
             select.select_by_visible_text(tvalue)
         elif tag == 'value':
             tvalue = self._matchOptionValue(target_elem, tvalue)
             select.select_by_value(tvalue)
         elif tag == 'id':
             option = target_elem.find_element_by_id(tvalue)
             select.select_by_visible_text(option.text)
         elif tag == 'index':
             select.select_by_index(int(tvalue))
         else:
             raise UnexpectedTagNameException("Unknown option locator tag: " + tag)
	def submitvlpform(self, vlpform):
		try: 
			firstname = vlpform.find_element_by_xpath(".//input[@name='first_name']")
			lastname = vlpform.find_element_by_xpath(".//input[@name='last_name']")
			email = vlpform.find_element_by_xpath(".//input[@name='email_address']")
			phone = vlpform.find_element_by_xpath(".//input[@name='phone']")
			company = vlpform.find_element_by_xpath(".//input[@name='company']")
			users = Select(vlpform.find_element_by_xpath(".//select[@name='vlp_intent']"))
			submit = vlpform.find_element_by_xpath(".//button")

			firstname.send_keys(self.fillfirstname)
			lastname.send_keys(self.filllastname)
			email.send_keys(self.fillemail)
			phone.send_keys(self.fillphone)
			company.send_keys(self.fillcompany)
			users.select_by_index(1)
			if self.dosubmit:
				submit.click()
			self.currentlog.append('success')
			self.writer.writerow(self.currentlog)
			self.currentlog = []
			time.sleep(2)
		except (NoSuchElementException, ElementNotVisibleException) as e:
			self.currentlog.append(e)
			self.writer.writerow(self.currentlog)
			self.currentlog = []
			return 'error'
Beispiel #11
0
    def scrape(self):
        self.driver.get(PLUGINFO['url'])

        select = Select(self.driver.find_element_by_name('findourpeople_searchfields$lstPracticeGroups'))
        option_indexes = range(1, len(select.options))

        for index in option_indexes:
            select.select_by_index(index)
            self.driver.find_element_by_id('findourpeople_searchfields_btnSubmitSearchQuery').click()

            s = BeautifulSoup(self.driver.page_source)
            r = re.compile(r'/contact-us/cvdetails-\d+.aspx\?')
            x = { 'class': 'ui-button', 'href': r }

            for a in s.findAll('a', attrs=x):
                tr = a.findParent('tr')
                td = tr.findAll('td')

                # URL, name, job title and location
                person = {}
                person['name'] = a.text
                person['url'] = urlparse.urljoin(self.driver.current_url, a['href'])
                person['job_title'] = td[2].text
                person['location'] = ''
                print person

            #
            # Reselect otherwise we get a Stale Element exception
            #
            select = Select(self.driver.find_element_by_name('findourpeople_searchfields$lstPracticeGroups'))

        self.driver.quit()
def test_add_meas_order_one_item(admin_client, live_server, webdriver):
    selenium = webdriver()
    selenium.implicitly_wait(3)
    try:
        create_correct_sample_data()
        num_orders_before = len(MeasurementOrder.objects.all())
        num_items_before = len(MeasurementItem.objects.all())
        selenium.get(live_server + '/new_item_and_order/')
        login_as_admin(selenium)
        order_type = Select(selenium.find_element_by_id('id_order_type'))
        order_type.select_by_index(1)
        selenium.find_element_by_name('action').click()
        assert selenium.current_url == live_server.url + '/new_item_and_order/'
        name = selenium.find_element_by_id('id_name')
        name.send_keys('Teddy the bear')
        selenium.find_element_by_name('action').click()
        assert selenium.current_url == live_server.url + '/new_item_and_order/'
        serial_nr = selenium.find_element_by_id('id_serial_nr')
        serial_nr.send_keys('4711')
        selenium.find_element_by_name('action').click()
        assert selenium.current_url == live_server.url + '/new_item_and_order/'
        product = Select(selenium.find_element_by_id('id_product'))
        product.select_by_index(1)
        selenium.find_element_by_name('action').click()
        wait_for_root_page(selenium)
        assert selenium.current_url == live_server.url + '/'
        assert len(MeasurementOrder.objects.all()) == num_orders_before + 1
        assert len(MeasurementItem.objects.all()) == num_items_before + 1
        assert MeasurementItem.objects.get(serial_nr=4711)
    finally:
        selenium.quit()
Beispiel #13
0
 def select_from_dropdown(self, locatortype, locator, value, reserve=None):
     # TODO: Id,CSS... locators
     if locatortype == "xpath":
         select = self.driver.find_element_by_xpath(locator)  #get the select element
         options = select.find_elements_by_tag_name("option") #get all the options into a list
         optionList = []
         # if reserve in None:
         for option in options:
             optionList.append(option.get_attribute("value"))
             optionList.append(option.text)
         for optionValue in optionList:
             if optionValue == value:
                 try:
                     select = Select(self.driver.find_element_by_xpath(locator))
                     select.select_by_value(value)
                     break
                 except NoSuchElementException:
                     self.driver.find_element_by_xpath(locator + "/option[contains(text(),'{0}')]".format(value)).click()
                     break
         else:
             # print("VALUE BROKEN! Select from reserve option number %s" % (reserve))
             if reserve is not None:
                 select = Select(self.driver.find_element_by_xpath(locator))
                 select.select_by_index(reserve)
             else:
                 return False
def login():
    #driver = webdriver.Firefox()
    link = "http://goarticles.com/members/"
    driver = firebug_proxy2.main(link)
    #driver.get(link)
    elem = driver.find_element_by_name("email")
    elem.send_keys("*****@*****.**")
    elem = driver.find_element_by_name("password")
    elem.send_keys("xxxxxxx")
    elem.send_keys(Keys.RETURN)
    #dir(driver)
    elem = driver.find_element_by_id("add_new")
    elem.send_keys(Keys.RETURN)
    select = Select(driver.find_element_by_name('category_id'))
    
    select.select_by_index(2)
    #select = Select(driver.find_element_by_name('sub_category_id'))
    #select.select_by_index(1)
    elem = driver.find_element_by_name("title")
    title  = "Different Ways You Can Define Yourself  "
    elem.send_keys(title)
    f = open("f1.html")
    body = f.read()
    body = unicode(body, errors='ignore')
    f.close()
    elem = driver.find_element_by_name("body")
    elem.send_keys(body)
    bio =" name  Kaya, just learing how to write a article"
    elem = driver.find_element_by_name("resource")
    elem.send_keys(bio)
    elem = driver.find_element_by_name("submit").click()
    #elem.submit() 
    time.sleep(5)
    driver.close()
    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)
def marketWalker():
    global driver,prevTrail
    try:
        showEol=waitVisible('#showEndLife')
        if not showEol.is_selected():
            showEol.click()
        selMkt= Select(waitVisible('.product-cat-box select:nth-child(1)'))
        startIdx=getStartIdx()
        numMkts = len(selMkt.options)
        curSel = selMkt.all_selected_options[0].text
        ulog('current Selected="%s"'%curSel)
        for idx in range(startIdx, numMkts):
            selMkt.select_by_index(idx)
            nextSel=selMkt.options[idx].text
            ulog('gonna select "%s"'%nextSel)
            btn = waitVisible('button.round-button.go')
            with UntilTextChanged('.content-box',9,0.4):
                btn.click()
            prevTrail+=[idx]
            modelWalker()
            prevTrail.pop()
            showEol=waitVisible('#showEndLife')
            if not showEol.is_selected():
                showEol.click()
            selMkt= Select(waitVisible('.product-cat-box select:nth-child(1)'))
    except Exception as ex:
        ipdb.set_trace()
        traceback.print_exc()
        driver.save_screenshot(getScriptName()+'_'+getFuncName()+'_exc.png')
Beispiel #17
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)
Beispiel #18
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)
def downloadFromList(driver, FROM, TO):
    selector2 = driver.find_element_by_xpath("//select[@name='saveToMenu']")
    options_for_second_selector = selector2.find_elements_by_tag_name("option")
    for option in options_for_second_selector:
        if (option.get_attribute('value') == 'other'):
            option.click()
            break

    radio_element = driver.find_element_by_name("value(record_select_type)")
    radio_element.click()

    from_element = driver.find_element_by_id("markFrom")
    from_element.send_keys(str(FROM))

    to_element = driver.find_element_by_id("markTo")
    to_element.send_keys(str(TO))

    select = Select(driver.find_element_by_id('bib_fields'))
    select.select_by_index(3)

    select = Select(driver.find_element_by_id('saveOptions'))
    select.select_by_index(1)

    thing = driver.find_element_by_class_name("quickoutput-action")
    thing.click()

    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, 'send'))
    )

    exitbutton = driver.find_element_by_class_name("quickoutput-cancel-action")
    exitbutton.click()
Beispiel #20
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)
def walkProdCat():
    global driver, prevTrail
    try:
        # click "Drilldown"
        waitClickable('#ctl00_ctl00_ctl00_mainContent_localizedContent_bodyCenter_BasicSearchPanel_btnAdvancedSearch')\
            .click()

        zpath = ('#ctl00_ctl00_ctl00_mainContent_localizedContent_bodyCenter_'+
                 'adsPanel_lbProductCategory')
        curSel = Select(css(zpath))
        numProdCats = len(curSel.options)
        ulog('numProdCats=%d'%numProdCats)

        startIdx = getStartIdx()
        for idx in range(startIdx, numProdCats):
            curSel = Select(css(zpath))
            ulog("idx=%s"%idx)
            ulog('select "%s"'%curSel.options[idx].text)
            curSel.select_by_index(idx)
            prevTrail+=[idx]
            walkProdFam()
            prevTrail.pop()
    except Exception as ex:
        traceback.print_exc(); ipdb.set_trace()
        driver.save_screenshot('netgear_exc.png')
Beispiel #22
0
 def test_can_create_community(self):
     self.make_admin()
     self.browser.get(self.live_server_url)
     self.browser.add_cookie(self.create_session_cookie())
     self.browser.refresh()
     self.browser.get('{}{}'.format(self.live_server_url, '/community/add_community/'))
     name = self.browser.find_element_by_id("id_name")
     slug = self.browser.find_element_by_id("id_slug")
     order = self.browser.find_element_by_id("id_order")
     email = self.browser.find_element_by_id("id_email")
     mailing_list = self.browser.find_element_by_id("id_mailing_list")
     parent_community = Select(
         self.browser.find_element_by_id("id_parent_community"))
     website = self.browser.find_element_by_id("id_website")
     facebook = self.browser.find_element_by_id("id_facebook")
     googleplus = self.browser.find_element_by_id("id_googleplus")
     twitter = self.browser.find_element_by_id("id_twitter")
     name.send_keys("Foo Community")
     slug.send_keys("foo-community")
     order.send_keys("5")
     email.send_keys("*****@*****.**")
     mailing_list.send_keys('*****@*****.**')
     parent_community.select_by_index(0)
     website.send_keys('http://www.foo-community.org')
     facebook.send_keys('http://www.facebook.com/foo-community')
     googleplus.send_keys('http://plus.google.com/foo-community')
     twitter.send_keys('http://www.twitter.com/foo-community')
     self.browser.find_element_by_id('submit-id-save').click()
     # Wait required on this page. Tests will fail without
     # wait even after successful completion of required actions.
     wait = WebDriverWait(self.browser, 10)
     wait.until(
         EC.presence_of_element_located(
             (By.XPATH, "//h1[contains(text(),'Foo Community')]")))
     self.assertTrue('Foo Community' in self.browser.title)
Beispiel #23
0
def testSelectByIndexSingle(driver, pages):
    pages.load("formPage.html")

    for select in [singleSelectValues1]:
        sel = Select(driver.find_element(By.NAME, select['name']))
        for x in range(len(select['values'])):
            sel.select_by_index(x)
            assert sel.first_selected_option.text == select['values'][x]
 def select_option(self, element, value, select_by="text"):
     select = Select(element)
     if select_by == "text":
         select.select_by_visible_text(value)
     elif select_by == "index":
         select.select_by_index(value)
     elif element.get("select_by") == "value":
         select.select_by_value(value)
    def testSelectByIndexSingle(self):
        self._loadPage("formPage")

        for select in [singleSelectValues1]:
            sel = Select(self.driver.find_element(By.NAME, select['name']))
            for x in range(len(select['values'])):
                sel.select_by_index(x)
                self.assertEqual(sel.first_selected_option.text, select['values'][x])
Beispiel #26
0
 def select_state(self, state=None):
     """Selects state from dropdown menu. If no state is provided, a random state is selected"""
     select = Select(self.driver.find_element(*MainPageLocators.STATE_DROPDOWN))
     if state==None:
         state_number = randint(1,50)
         select.select_by_index(state_number)
     else:
         select.select_by_visible_text(state)
Beispiel #27
0
 def select(self, text=None, index=None, selector=None):
     elem = self.find(selector)
     sel = Select(elem.wd)
     if text is not None:
         sel.select_by_visible_text(text)
     elif index is not None:
         sel.select_by_index(index)
     return elem
 def test_select_drop_down_option(self):
     self.driver.get(self.base_url + "store/p4/Lope_Lunch_By_The_Pool.html")
     drop_down_id = "wsite-com-product-option-Quantity"
     drop_down_element = self.wait.until(lambda driver: driver.find_element_by_id(drop_down_id))
     select = Select(drop_down_element)
     select.select_by_visible_text("2")
     select.select_by_index(0)
     select.select_by_value("1")
Beispiel #29
0
def main():
	evalPagesNew = []
	evalPagesOld = []
	evals = []
	driver = webdriver.Firefox()
	driver.implicitly_wait(20)
	driver.get("https://edu-apps.mit.edu/ose-rpt/?Search+Online+Reports=Search+Subject+Evaluation+Reports")
	#Authentication
	driver.find_element_by_name("j_username").send_keys("USERNAME")
	driver.find_element_by_name("j_password").send_keys("PASSWORD")
	driver.find_element_by_name("Submit").click()
	#Wait until next page loads
	checkProgress = False
	while(not checkProgress):
		checkProgress = "Subject Evaluation Report Search" in driver.title
	checkProgress = False
	#Iterate through each term; start at index 1 because index 0 is Any Term
	numTerms = len(driver.find_elements_by_xpath("//select[@id='term']/option"))
	for i in range(1, 50):
		old = False
		#Subject eval forms changed after Fall Term 2009-2010 (except January Term 2009-2010)
		if(i == 17 or i > 18):
			old = True
		select = Select(driver.find_element_by_xpath("//select[@id='term']"))
		select.select_by_index(i)
		driver.find_element_by_name("search").click()
		while(not checkProgress):
			checkProgress = "Search Results" in driver.title
		checkProgress = False
		#Three p tags before links to subject evals start
		numClassesPlus3 = len(driver.find_elements_by_xpath("//div[@id='rh-col']/p"))
		#Iterate through each class
		for j in range(4, numClassesPlus3):
			driver.find_element_by_xpath("//div[@id='rh-col']/p[%i]/a" % j).click()
			while(not checkProgress):
				checkProgress = "Report for" in driver.title
			checkProgress = False
			if(old == False):
				evalPagesNew.append(BeautifulSoup(driver.page_source))
			elif(old == True):
				evalPagesOld.append(BeautifulSoup(driver.page_source))
			driver.back()
			if(j>7):
				break
		driver.back()
		if(i>2):
			break
	driver.close()

	#Parse enew vals
	for evalPage in evalPagesOld:
		evals.append(htmlParse(evalPage))
	for evalPage in evalPagesNew:
		evals.append(htmlParse(evalPage))

	

	for Eval in evals:
    def testSelectDisabledByIndexShouldThrowException(self):
        self._loadPage("formPage")

        try:
            sel = Select(self.driver.find_element(By.NAME, disabledSelect['name']))
            sel.select_by_index(0)
            raise Exception("Didn't get an expected ElementNotSelectableException exception.")
        except ElementNotSelectableException:
            pass # should get this exception
Beispiel #31
0
# from selenium import webdriver
#
# # chromedriver 的目录路径
# driver_path = r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'
# # 用的浏览器名称  和目录路径
# driver = webdriver.Chrome(executable_path=driver_path)
# # 请求的网站
# driver.get("https://www.douban.com/")
# remberBtn = driver.find_element_by_id('account-form-remember')
# # 选中 鼠标点击
# remberBtn.click()

# 操作select标签
from selenium import webdriver
from selenium.webdriver.support.ui import Select
# chromedriver 的目录路径
driver_path = r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'
# 用的浏览器名称  和目录路径
driver = webdriver.Chrome(executable_path=driver_path)
# 请求的网站
driver.get("https://www.douban.com/")
# 包装一下
selectbtn = Select(driver.find_element_by_id('account-form-remember'))
# 下拉列表中第一个
selectbtn.select_by_index(1)
# 也可以根据值来即内容
selectbtn.select_by_value(".....")
# 也可以根据他显示的选项来操作
selectbtn.select_by_visible_text(".....")
# 取消选中的所有选项
selectbtn.deselect_all()
Beispiel #32
0
def applyGreenhouse(logger, file_path):
    current_url = browser.driver.current_url
    logger.info('Starting at page: {}'.format(current_url))
    form_id = [
        "first_name", "last_name", "email", "phone", "job_application_location"
    ]

    form_values = [
        "Huyanh", "Hoang", "*****@*****.**", "5626661609",
        "Irvine, California, United States"
    ]

    inputs = []
    # TODO: potential bug: id isnt there but the values are by name i.e. pinterest
    for i, text in zip(form_id, form_values):
        element = browser.findElementByID(i)
        # bug in pychrome? if cant find element it overrides previous element if didnt check for 0
        if element:
            inputs.append(True)
            browser.sendTextToElement(text, element)

    # for now we hard code the click.
    location = browser.findElementByID('job_application_location')
    # if location not found then it will use the previous item found, PyChrome issue
    if location:
        browser.sendTextToElement('Irvine, California, United States',
                                  location)
        location_item = browser.findElementByClass('ui-menu-item')
        browser.findElementByTag('div', location_item).click()

    if len(inputs) == 0:
        logging.error(
            "None of the standard inputs filled, saving application: {}".
            format(current_url))
        dictionary_builder.save_question(current_url,
                                         "Standard inputs not filled")
    try:
        file_element = browser.findElementByID("file")
        file_element.send_keys(file_path)
    except AttributeError:
        logging.error('File upload error, element does not exist')

    custom = browser.findElementByID("custom_fields")
    field = browser.findElementByTag("div", custom)
    siblings = browser.findSiblingsElements()
    for element in siblings:
        label = browser.findElementByTag("label", element)
        if label and "*" in label.text:
            # check if the question exists in our dictionary
            question = dictionary_builder.check_question(
                phrase=label.text.split("\n")[0], kw_dict=keyword_dict)
            if question:
                answer = questions_dict[question]
                answers = questions_dict[question].split("|")
                input_box = browser.findElement(element=label,
                                                css="input[type=text]")
                if not input_box:
                    dropdown = browser.findElementByTag("select", label)
                    if dropdown:
                        select = Select(dropdown)
                        logger.info("Dropdown found")
                        if "Yes" in dropdown.text and "No" in dropdown.text:
                            try:
                                logger.info("Yes/No question found")
                                select.select_by_visible_text(answer)
                            except NoSuchElementException:
                                logger.error(
                                    'Could not fill out yes/no question: {}'.
                                    format(dropdown.text))
                        else:
                            logger.info("Not a Yes/No question")
                            logger.info('Questions: {}'.format(select.options))

                            def find_answer():
                                for _i, option in enumerate(select.options):
                                    for answer in answers:
                                        if answer in option.text:
                                            select.select_by_index(_i)
                                            return answer
                                return 0

                            if not find_answer():
                                select.select_by_index(1)
                                logger.info(
                                    'Nothing in dict, selecting "{}"'.format(
                                        select.first_selected_option))
                    elif browser.findElementByTag(
                            'label', label):  # find the direct child label
                        find_checkbox()
                    else:
                        logger.error(
                            "Neither dropdown nor input (No tags found)")
                else:
                    try:
                        input_box.send_keys(answer)
                    except:
                        logger.error("Element isn't valid")
            else:
                question_to_save = label.text.split('\n')[0]
                logging.warning('Question not in graph, saving: {}'.format(
                    question_to_save))
                dictionary_builder.save_question(current_url,
                                                 'Question not in graph',
                                                 question_to_save)
        else:
            logger.warning('Label does not exist or not required')
    logger.info("Finished answering questions")
    try:
        WebDriverWait(browser.driver, 5).until(
            expected_conditions.text_to_be_present_in_element(
                (By.ID, 'resume_filename'), 'HuyanhHoang-Resume.pdf'))
    except TimeoutException:
        logger.error('Resume was not uploaded, save file here')
        dictionary_builder.save_question(current_url, 'Resume not uploaded')
        return 0
Beispiel #33
0
 def book(self):  #预约挂号
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/div[3]/aside/section/ul/li[3]/a/span[1]')
                                      ).click()  # 点击预约挂号
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="registerName_input"]')).send_keys(u"董焕焕")  #输入姓名
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="appointment_nav"]/ul')).click()  # 点击空白处
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="telephonNum"]')).send_keys(
             "18611059298")  #输入手机号
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="sexWoman"]')).click()  #选择女
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="registAgeInput"]')).send_keys(25)  #输入年龄
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-costTypeName-container"]')).click(
         )  #点击费别处的请选择
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"VIP")  #在费别处输入VIP
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #选择VIP
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="atureFlage"]')).click()  #勾选保险支付
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-InsureCompanyList-container"]')).click(
         )  #点击保险信息处的请选择
     time.sleep(1)
     WebDriverWait(browser, 10).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"兴业银行")  #输入兴业银行
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  # 选择兴业银行
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="registInsureNum"]')).send_keys(123456)  #输入保险号
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="appointment_nav"]/ul')).click()  # 点击空白处
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="register_deductible"]')).send_keys(
             u"99.99")  #输入自付款
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="register_CoInsurance"]')).send_keys(
             u"0.87654321")  #输入自付比例
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="register_copayment"]')).send_keys(
             u'0.88')  #输入定额手续费
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="register_insure_remark"]')).send_keys(
             u"每年最高报销100万")  #输入备注
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-zhenfee_select-container"]')).click(
         )  #点击诊费处的请选择
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"常规诊费")  #输入常规诊费
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #选择常规诊费
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="appointment_nav"]/ul')).click()  # 点击空白处
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-Order_startTime-container"]')).click(
         )  #点击就诊时间的开始时间
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"8:00")  #就诊时间的开始时间输入9:00
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #就诊时间的开始时间选择9:00
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-Order_endTime-container"]')).click(
         )  #点击结束时间
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"8:30")  #在结束时间输入10:00
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #选择10:00
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="1002"]')).click()  #就诊事项选择打针
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="1004"]')).click()  # 就诊事项选择取药
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="1006"]')).click()  # 就诊事项选择推拿
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="itemsNose"]')).send_keys(u"青霉素过敏")  #备注处输入青霉素过敏
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="pationtDtailBtn"]/small')).click()  #患者详细信息处点击展开
     target = WebDriverWait(browser, 30).until(
         lambda x: x.find_element("xpath", '//*[@id="addressDetail"]'))
     browser.execute_script("arguments[0].scrollIntoView();",
                            target)  # 滑动到地址处
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="medicareCardNum"]')).send_keys(123456)
     time.sleep(1)
     s1 = Select(
         WebDriverWait(browser, 30).until(
             lambda x: x.find_element("id", "credentialType")))  #下拉框的选择
     s1.select_by_index("1")  #下拉框的选择军官证
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="credentialTypeNum"]')).send_keys(
             1234567890)  #输入军官证号
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-country-container"]')).click(
         )  #点击民族处的国籍
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"中国")  #在国籍处输入中国
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #选择中国
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-national-container"]')).click()  #点击民族
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"维吾尔族")  #输入维吾尔族
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #选择维吾尔族
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="maritalStatus"]')).click()  #点击婚姻状态处的请选择
     time.sleep(1)
     t1 = Select(
         WebDriverWait(browser, 30).until(
             lambda x: x.find_element("id", "maritalStatus")))  # 下拉框的选择
     t1.select_by_index("1")  # 下拉框的选择已婚
     time.sleep(1)
     WebDriverWait(browser, 30).until(
         lambda x: x.find_element("xpath", '//*[@id="work"]')).send_keys(
             u"测试工程师")  #输入职业
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="companyName"]')).send_keys(
             u"泓华国际医疗控股有限公司")  #输入工作单位
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-province-container"]')).click(
         )  #选择住址处的省
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(u"北京")  #
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-city-container"]')).click()  #选择住址处的市
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"北京市")  #
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="select2-district-container"]')).click(
         )  #选择住址处的区
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             u"朝阳区")  #
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '/html/body/span/span/span[1]/input')).send_keys(
             Keys.ENTER)  #
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="addressDetail"]')).send_keys(
             u"北辰东路北辰汇宾大厦B座19层")  #填写详细地址
     target = WebDriverWait(browser, 30).until(
         lambda x: x.find_element("xpath", '//*[@id="weight"]'))  # 滑动到体重处
     browser.execute_script("arguments[0].scrollIntoView();",
                            target)  # 滑动到体重处
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="temperature"]')).send_keys(37)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="heartRateNow"]')).send_keys(70)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="breatheNow"]')).send_keys(80)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="pulseRateNow"]')).send_keys(90)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="BP_hight"]')).send_keys(120)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="BP_low"]')).send_keys(90)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="height"]')).send_keys(160)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="weight"]')).send_keys(60)
     target = WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="historyShowBtn"]'))  #滑动到病史信息
     browser.execute_script("arguments[0].scrollIntoView();", target)  #
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="historyShowBtn"]/small')).click()  #点击病史信息处的展开
     time.sleep(1)
     target = WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="allergiesHistory"]'))  # 滑动到过敏史处
     browser.execute_script("arguments[0].scrollIntoView();",
                            target)  # 滑动到过敏史处
     time.sleep(1)
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="historyOfPresentIllness"]')).send_keys(u"偏头痛")
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="personalHistory"]')).send_keys(u"失眠、多梦")
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="allergiesHistory"]')).send_keys(u"青霉素过敏")
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="pastHistory"]')).send_keys(u"失眠、多梦")
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="familyHistory"]')).send_keys(u"近视眼")
     WebDriverWait(browser, 30).until(lambda x: x.find_element(
         "xpath", '//*[@id="addRegister_save"]')).click()  #点击保存
     print("预约挂号成功")
Beispiel #34
0
# Set wait for the driver
driver_wait = WebDriverWait(driver, wait_time)

dropdown_element = driver_wait.until(EC.element_to_be_clickable(
    (By.ID, 'CMA')))
dropdown_list = dropdown_element.text.split('\n')

for dropdown_index in range(len(dropdown_list)):

    print(dropdown_index, dropdown_list[dropdown_index])

    dropdown_element = driver_wait.until(
        EC.element_to_be_clickable((By.ID, 'CMA')))
    selected_dropdown_element = Select(dropdown_element)
    selected_dropdown_element.select_by_index(dropdown_index)

    submit_element = driver_wait.until(
        EC.element_to_be_clickable((By.ID, 'subgeo')))
    submit_element.click()

    tbody_elements = driver.find_elements_by_tag_name('tbody')
    #tbody_elements[0] is the blank header row
    tbody_element = tbody_elements[1]

    tr_elements = tbody_element.find_elements_by_tag_name('tr')
    for tr_element in tr_elements:

        list_values = []
        list_values.append(dropdown_list[dropdown_index])
Beispiel #35
0
from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome(
    executable_path=
    "C:\\Users\\MANIKANTA\\Downloads\\new\\chromedriver_win32 (2)\\chromedriver.exe"
)
driver.get("http://demo.automationtesting.in/Register.html")

mani = driver.find_element_by_id("Skills")
k = Select(mani)

# k.select_by_visible_text('CSS')
k.select_by_index('16')
driver.maximize_window()
print(len(k.options))
s = k.options
for v in s:
    print(v.text)
print(driver.current_url)
driver.quit()
Beispiel #36
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome(
    executable_path="C:\\python\\Python_Drivers\\chromedriver.exe")
driver.get("https://krninformatix.com/sample.html")
driver.implicitly_wait(2)
# Method1 drop=Select(driver.find_element_by_id("city"))
element = driver.find_element_by_id("city")
drp = Select(element)

# we can identify in 3 methods

# select by visible text
drp.select_by_visible_text('Chennai')

# select by index. Index start from 0
drp.select_by_index(0)  # select by bangalore

# select by value
drp.select_by_value('3')  # select by mumbai

# count all drop down options
print(len(drp.options))

allOptions = drp.options

for option in allOptions:
    print(option.text)
Beispiel #37
0
    def digit_rule(self):

        logging.info("Lets get started for digit rule Profile sub-module")

        try:
            logging.info("Reading data from xlsx file")
            x = "Read\Switch.xlsx"
            r = get_data(x, 4)
            c = get_data(x, 5)
            for i in range(0, len(c)):
                print "value of %s parameter is : %s" % (r[i], c[i])
                logging.info("value of %s parameter is : %s" % (r[i], c[i]))
            logging.info("Data reading functionality completed successfully")
        except:
            logging.error("file path related issue")

        self.driver.refresh()
        time.sleep(5)
        self.driver.find_element_by_css_selector(
            "li.switch > a > div.menu_name").click()
        time.sleep(5)
        self.driver.find_element_by_link_text("Digit Rule").click()
        time.sleep(5)
        logging.info("Creating digit rule using ADD form")
        self.driver.find_element_by_id("sbtRuleAdded").click()
        time.sleep(2)
        self.driver.find_element_by_id("txtDigitRuleName").send_keys(c[0])
        digit_rule_type = Decimal(c[8])
        if (digit_rule_type == 1):
            logging.info("Creating vendor digit rule...")
            self.driver.find_element_by_id("rdoDigitRuleType-1").click()
        else:
            logging.info("Creating Customer digit rule..")
            self.driver.find_element_by_id("txtMinDNIDLength").clear()
            self.driver.find_element_by_id("txtMinDNIDLength").send_keys(
                Decimal(c[3]))
            self.driver.find_element_by_id("txtMaxDNIDLength").clear()
            self.driver.find_element_by_id("txtMaxDNIDLength").send_keys(
                Decimal(c[4]))

        self.driver.find_element_by_id("txtANI").send_keys(c[1])
        self.driver.find_element_by_id("txtDNID").send_keys(c[2])
        ANI_Rule = Select(self.driver.find_element_by_id("cmbANIRuleType"))
        ANI_Rule.select_by_index(0)
        ANI_Left_Strip = Select(
            self.driver.find_element_by_id("cmbANILeftStrip"))
        ANI_Left_Strip.select_by_index(1)
        ANI_Right_Strip = Select(
            self.driver.find_element_by_id("cmbANIRightStrip"))
        ANI_Right_Strip.select_by_index(1)
        DNID_Rule = Select(self.driver.find_element_by_id("cmbDNIDRuleType"))
        DNID_Rule.select_by_index(0)
        ANI_Left_Strip = Select(
            self.driver.find_element_by_id("cmbDNDILeftStrip"))
        ANI_Left_Strip.select_by_index(1)
        ANI_Right_Strip = Select(
            self.driver.find_element_by_id("cmbDNDIRightStrip"))
        ANI_Right_Strip.select_by_index(1)
        self.driver.find_element_by_css_selector(
            "#sbtRuleadd > div.button_text").click()
        logging.info("Digit rule has been added Successfully")
        time.sleep(5)

        try:
            self.driver.find_element_by_class_name("ui-button-text").click()
            return "PASS"
        except:
            return "FAIL"
Beispiel #38
0
print(username)
print(lastname)

## Try to Login with the new user ##
driver.get('http://localhost:3000/portal/org-test-parent/login')

# Wait for the page to load
wait = WebDriverWait(driver, 10)
elem = wait.until(EC.element_to_be_clickable((By.ID, 'username')))

# Fill the login fields
elem = driver.find_element_by_id("username")
elem.send_keys(username)
elem = driver.find_element_by_id("password")
elem.send_keys(lastname)

# Try to log in an unregistered group
select = Select(driver.find_element_by_id("group"))
select.select_by_index(2)
btn = driver.find_element_by_xpath("//button[text()='Log in']")
btn.click()

try:
    error = driver.find_element_by_class_name('login-error-wrapper')
except NoSuchElementException:
    print('Success')
else:
    print('Error Page')

# driver.quit()
# selenium.common.exceptions
Beispiel #39
0
def sendMessage(sendMessageUrl, modelStr, driver, orderid):
    # 循环的目的是为了在发生未知错误时,能够重新进行一次
    while True:
        try:
            # 选择subject为order Infomation
            print('start to send')
            bMutex.lock()
            driver.get(sendMessageUrl)
            bMutex.unlock()
            time.sleep(2)
            bMutex.lock()
            selectButtonWait = wait.WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located(
                    (By.ID, 'commMgrCompositionSubject')))
            selectSubject = Select(
                driver.find_element_by_id('commMgrCompositionSubject'))
            selectSubject.select_by_index(1)

            # 获取名字
            twoNameDiv = driver.find_elements_by_css_selector(
                "[style='padding-bottom:2px']")
            name = twoNameDiv[0].text.strip()
            p = re.compile(r':(.*)\(')
            t = re.search(p, name)
            name = t.group(1)
            # 获取订单详情
            productname = driver.find_element_by_css_selector(
                "[style='list-style-position:inside; padding-left:0; margin-left:0']"
            ).text
            bMutex.unlock()

            if len(productname) > 80:
                productname = tool.getorderinfo2(driver, orderid)

            # 对model进行智能处理
            patternOrderid = re.compile(r'#orderid')
            patternUsername = re.compile(r'#username')
            patternProductname = re.compile(r'#productname')
            modelStr = re.sub(patternOrderid, orderid, modelStr)
            modelStr = re.sub(patternUsername, name, modelStr)
            modelStr = re.sub(patternProductname, productname, modelStr)
            modelStr = '%r' % modelStr
            # 发送的内容
            # modelStr = 'dear '+name+':\n'+modelStr
            bMutex.lock()
            wait.WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located(
                    (By.ID, 'commMgrCompositionMessage')))
            textArea = driver.find_element_by_id('commMgrCompositionMessage')
            driver.execute_script("arguments[0].value=" + modelStr + ";",
                                  textArea)
            bMutex.unlock()
            time.sleep(1)

            # 点击发送邮件按钮
            bMutex.lock()
            wait.WebDriverWait(driver, 10).until(
                EC.presence_of_all_elements_located(
                    (By.CSS_SELECTOR, '#sendemail_label')))
            allSendMailLabel = driver.find_elements_by_css_selector(
                '#sendemail')
            allSendMailLabel = allSendMailLabel[1]
            driver.execute_script("arguments[0].click();", allSendMailLabel)

            # 点了发送休息2S
            # time.sleep(3)
            wait.WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.NAME, 'Back to Manage Orders')))
            bMutex.unlock()
            print('send OK')
            return name
        except Exception as e:
            bMutex.unlock()
            traceback.print_exc()
            print('try send again----------------------')
Beispiel #40
0
    yield
    WebDriverWait(driver_, timeout).until(staleness_of(old_page))


driver = webdriver.Firefox()

# Root presidential elections link
driver.get(
    "http://www.vybory.izbirkom.ru/region/izbirkom?action=show&root_a=12000009&vrn=100100084849062&region=0&global=true&type=0&prver=0&pronetvd=null"
)

# Iterate over every region
dropRegion = Select(driver.find_element(By.NAME, "gs"))
for i in range(1, len(dropRegion.options) - 1):
    dropRegion = Select(driver.find_element(By.NAME, "gs"))
    dropRegion.select_by_index(i)
    region_name = dropRegion.first_selected_option.text
    driver.find_element(By.NAME, "go").click()

    # Iterate over every subregion
    dropSubRegion = Select(driver.find_element(By.NAME, "gs"))
    for j in range(1, len(dropSubRegion.options) - 1):
        dropSubRegion = Select(driver.find_element(By.NAME, "gs"))
        dropSubRegion.select_by_index(j)
        subregion_name = dropSubRegion.first_selected_option.text
        driver.find_element(By.NAME, "go").click()
        driver.find_element(
            By.LINK_TEXT,
            "сайт избирательной комиссии субъекта Российской Федерации").click(
            )
        wait_for_page_load(driver)
def __parse_option_open_interest_table(driver, *args, **kwargs):
    # import pdb; pdb.set_trace()
    max_data_count = kwargs.get("max_data_count", DEF_MAX_DATA_COUNT)
    assert 1 <= max_data_count <= MAX_DATA_DAY_NUMBER, "max_data_count[%d] should be in the range: [1, %d]" % (
        max_data_count, MAX_DATA_DAY_NUMBER)
    wait = WebDriverWait(driver, 15)

    data_list = []
    data_name_list = None
    for count in range(max_data_count):
        # import pdb; pdb.set_trace()
        index = MAX_DATA_DAY_NUMBER - 1 - count
        # Select the date
        if count != 0:
            xpath = "//*[@id='CPHB1_Options1_rdoDates_%d']" % index
            date_input = driver.find_element_by_xpath(xpath)
            # print date_input.get_attribute("value") // Can get the date string
            date_input.click()
# Wait for the select
        option_select = wait.until(
            EC.presence_of_element_located(
                (By.ID, "CPHB1_Options1_ddlEndDates")))
        # option_select = driver.find_element_by_id("CPHB1_Options1_ddlEndDates")
        option_item_list = [
            x.get_attribute("value")
            for x in option_select.find_elements_by_tag_name("option")
        ]
        # print option_item_list
        # Count weekly option
        weekly_option_count = len(
            filter(lambda x: re.match("[\d]+W[\d]", x), option_item_list))
        assert (
            weekly_option_count >= 0 and weekly_option_count <= 2
        ), "Incorrect weekly option count, option_item_list: %s" % option_item_list
        # import pdb; pdb.set_trace()
        is_weekly = kwargs.get("is_weekly", False)
        option_select_index = 0
        if is_weekly:
            # import pdb; pdb.set_trace()
            if weekly_option_count == 0:
                option_select_index = 0
            else:
                option_select_index = weekly_option_count - 1
        else:
            if weekly_option_count == 0:
                option_select_index = 1
            else:
                option_select_index = weekly_option_count
        # print "option_item_list: %s, option_select_index: %d" % (option_item_list, option_select_index)


# Select the expiry date
        table_element = None
        if option_select_index != 0:
            option_select = Select(option_select)
            option_select.select_by_index(option_select_index)
            # Wait for the table
            wait = WebDriverWait(driver, 10)
            table_element = wait.until(
                EC.presence_of_element_located((
                    By.XPATH,
                    "/html/body/form/div[4]/div[5]/div/div/div[2]/div[2]/div/table"
                )))
        else:
            table_element = driver.find_element_by_xpath(
                "/html/body/form/div[4]/div[5]/div/div/div[2]/div[2]/div/table"
            )
        tr_elements = table_element.find_elements_by_tag_name("tr")
        # Parse the date string
        xpath = "//*[@id='CPHB1_Options1_rdoDates']/tbody/tr/td[%d]/label" % (
            index + 1)
        date_label = driver.find_element_by_xpath(xpath)
        date_element_list = map(int, date_label.text.split("/"))
        assert len(
            date_element_list
        ) == 3, "date_element_list[%s] length should be 3" % date_element_list
        date_string = CMN.DEF.DATE_STRING_FORMAT % (
            date_element_list[0], date_element_list[1], date_element_list[2])
        # print "date string: %s" % date_string
        single_date_data_list, data_name_list_tmp = __parse_table(
            driver, count, date_string, tr_elements, **kwargs)
        data_list.append(single_date_data_list)
        if data_name_list is None:
            data_name_list = data_name_list_tmp
    # import pdb; pdb.set_trace()
    data_list.reverse()
    return (data_list, data_name_list)
Beispiel #42
0
 def set_tcls(self):
     sel_tcls = Select(
         browser.find_element_by_xpath('//*[@id="custom_field_7_4"]'))
     sel_tcls.deselect_all()
     sel_tcls.select_by_index(self.tcls)
Beispiel #43
0
 def set_status(self):
     sel_stat = Select(
         browser.find_element_by_xpath('//*[@id="tc_status"]'))
     sel_stat.select_by_index(self.stat)
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import Select
# read html from BNM website
url = ('https://www.bnm.gov.my/index.php?' +
       'ch=statistic&pg=stats_exchangerates')
browser = webdriver.Chrome()
browser.get(url)

# select starting day and year from drop down menu
ddelement = Select(
    browser.find_element_by_xpath(
        "/html/body/div[1]/div/div[2]/div/section/div/div/div/div/div[2]/div/form/div[1]/div[1]/select[1]"
    ))
ddelement.select_by_index(0)
ddelement = Select(
    browser.find_element_by_xpath(
        "/html/body/div[1]/div/div[2]/div/section/div/div/div/div/div[2]/div/form/div[1]/div[1]/select[2]"
    ))
ddelement.select_by_value("2015")
browser.find_element_by_xpath(
    "/html/body/div[1]/div/div[2]/div/section/div/div/div/div/div[2]/div/form/div[2]/div[4]/input"
).click()
time.sleep(2)

# extracting table from page
data = pd.read_html(browser.page_source)[0]
browser.close()

# keep only the first three columns
Beispiel #45
0
    def toubaochuli(self):
        self.driver = webdriver.Ie()
        self.driver.maximize_window()
        self.driver.get(url)
        self.driver.find_element_by_id("username").send_keys(tbun)
        self.driver.find_element_by_id("password").send_keys(pw)
        self.driver.find_element_by_id("bt_submit").submit()
        time.sleep(2)
        self.driver.switch_to.frame("leftFrame")
        self.driver.find_element_by_link_text("承保子系统").click()
        self.driver.find_element_by_link_text("投保管理").click()
        self.driver.find_element_by_link_text("投保处理").click()

        self.driver.switch_to.default_content()
        self.driver.switch_to.frame("mainFrame")
        self.driver.find_elements_by_name('planrisk')[1].click()

        self.driver.find_element_by_css_selector("input[name='planCode']").send_keys("1360")
        self.driver.find_element_by_css_selector("input[value='下一步']").click()


        self.driver.switch_to.frame("myFrame")
        #直接业务
        ser = Select(self.driver.find_element_by_css_selector("select[name='GuMainBusinessMode']"))
        ser.select_by_index(0)

        ej = 'var q = document.getElementsByName("GuMainChannelDetailCode");q[0].value = "%s";' % "0101"
        self.driver.execute_script(ej)

        self.driver.find_element_by_css_selector("input[name='GuMainChannelDetailCode']").send_keys(Keys.TAB)
        sj = 'var q = document.getElementsByName("GuMainChannelTip");q[0].value = "%s";' % "01010102"
        self.driver.execute_script(sj)

        ywgs = 'var q = document.getElementsByName("GuMainCompanyCode");q[0].value = "%s";' % "0104000001"
        self.driver.execute_script(ywgs)

        ywy = 'var q = document.getElementsByName("GuMainSalesmanCode");q[0].value = "%s";' % "S000000081"
        self.driver.execute_script(ywy)

        bdgs = 'var q = document.getElementsByName("GuMainCityCode");q[0].value = "%s";' % "110000"
        self.driver.execute_script(bdgs)

        bdgx = 'var q = document.getElementsByName("GuMainCountyCode");q[0].value = "%s";' % "110101"
        self.driver.execute_script(bdgx)


        #身份证采集
        __win = self.driver.current_window_handle
        self.driver.find_element_by_css_selector("input[name='buttonAppliIdentifyGenerate']").click()
        __all = self.driver.window_handles
        for h in __all:
            if h != __win:
                self.driver.switch_to.window(h)
                time.sleep(2)
                self.driver.find_element_by_css_selector("input[id='Text1']").send_keys(tbname)          #姓名
                self.driver.find_element_by_css_selector("input[id='Text2']").send_keys(sex)             #性别
                self.driver.find_element_by_css_selector("input[id='Text3']").send_keys(minzu)           #民族
                self.driver.find_element_by_css_selector("input[id='Text4']").send_keys(birday)          #出生日期
                self.driver.find_element_by_css_selector("TEXTAREA[name='Address']").send_keys(address)  #地址
                self.driver.find_element_by_css_selector("input[id='Text6']").send_keys(id)              #身份证
                self.driver.find_element_by_css_selector("input[id='Text7']").send_keys("北京市公安局")    #身份证签发机构
                self.driver.find_element_by_css_selector("input[id='Text8']").send_keys("2010.10.10")    #身份证有效期起期
                self.driver.find_element_by_css_selector("input[id='Text10']").send_keys("2020.10.10")   #身份证有效期止期
                self.driver.find_element_by_css_selector("input[value='确定']").click()
                self.driver.switch_to.window(__win)
                self.driver.switch_to.frame("mainFrame")
                self.driver.switch_to.frame("myFrame")
        self.driver.find_element_by_css_selector("input[name='AppliGuRelatedPartyMobilePhone']").send_keys(tel)#电话
        self.driver.find_element_by_css_selector("input[name='AppliGuRelatedPartyPostCode']").send_keys(postcode)
        self.driver.find_element_by_css_selector("input[name='buttonInsuredGuAppliPartyCustomerIdentify']").click()#客户识别
        self.alert_acc()

        self.driver.find_element_by_css_selector("input[name='buttonSaveCustomer']").click()#保存客户
        self.alert_acc()
        self.driver.find_element_by_css_selector("input[name='buttonCourierInfoCollect']").click()#配送信息
        self.driver.find_element_by_css_selector("input[value='关闭']").click()#关闭
        self.driver.find_element_by_css_selector("input[name='saveButton']").click()#保存
        #进入标的信息
        self.driver.switch_to_default_content()
        self.driver.switch_to.frame("mainFrame")
        self.driver.switch_to.frame("myFrame")
        self.driver.find_element_by_css_selector("input[name='GuItemMotorPhoneNumber']").send_keys(tel)#车主手机电话
        self.driver.find_element_by_css_selector("input[name='GuItemMotorLicenseNo']").send_keys(carnb)#号牌号码

        __win1 = self.driver.current_window_handle
        self.driver.find_element_by_css_selector("input[name='detailQuery']").click() #车型查询
        __all1 = self.driver.window_handles
        for h in __all1:
            if h != __win1:
                self.driver.switch_to.window(h)
                self.driver.find_element_by_css_selector("input[name='GuItemMotorLicenseNo']").send_keys(carnb)
                self.driver.find_element_by_css_selector("input[name='GuItemMotorFrameNo']").send_keys(chejiahao)
                self.driver.find_element_by_css_selector("input[value='查询(Q)']").click()
                self.driver.switch_to.frame("QueryResultFrame")
                time.sleep(2)
                self.driver.find_element_by_css_selector("input[name='GuItemMotorLicenseTypeCode']").send_keys("02")
                self.driver.find_element_by_css_selector("input[name='GuItemMotorCarBrand']").send_keys(caricon)#车辆品牌
                self.driver.find_element_by_css_selector("input[name='GuItemMotorCarKindBCode']").send_keys("A")#车辆大类
                self.driver.find_element_by_css_selector("input[name='GuItemMotorCarKindCode']").send_keys("A0")#车辆种类
                self.driver.find_element_by_css_selector("input[name='GuItemMotorUseNatureShow']").send_keys("8A")#使用性质
                self.driver.find_element_by_css_selector("input[name='GuItemMotorEnrollDate']").send_keys("2015-12-12")#车辆日期日期
                self.driver.find_element_by_css_selector("input[name='checkboxSelect']").click()
                self.driver.find_element_by_css_selector("input[value='查询(Q)']").click()
                time.sleep(2)
                self.driver.find_element_by_css_selector("input[name='checkboxSelect']").click()
                self.driver.find_element_by_css_selector("input[value='选择']").click()
                self.driver.switch_to.window(__win1)
        time.sleep(1)
        self.driver.switch_to_default_content()
        self.driver.switch_to.frame("mainFrame")
        self.driver.switch_to.frame("myFrame")

        self.driver.find_element_by_css_selector("input[name='GuItemMotorAttachNature']").send_keys("01")    #车主性质
        self.driver.find_element_by_css_selector("input[name='GuItemMotorVehicleCategory']").send_keys("K33")#交管车辆类型
        self.driver.find_elements_by_css_selector("input[name='ItemMotorCarCheckReason']")[4].click()        #协议免验
        self.driver.find_element_by_css_selector("body > div > form > div:nth-child(69) > input").click()
        #险种信息
        time.sleep(2)
        self.driver.switch_to.default_content()
        self.driver.switch_to.frame("mainFrame")
        self.driver.switch_to.frame("myFrame")
        self.driver.switch_to.frame("RiskFrame")
        self.driver.switch_to_frame("myFrame")
        self.driver.find_element_by_css_selector("input[value='带入投保人信息']").click()#带入投保人信息
Beispiel #46
0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome(executable_path="drivers/chromedriver.exe")
driver.get("https://opensource-demo.orangehrmlive.com/")
driver.maximize_window()
username = driver.find_element(By.NAME, "txtUsername")
username.send_keys("admin")
password = driver.find_element(By.XPATH, "//input[@type='password']")
password.send_keys("admin123")
time.sleep(1)
login = driver.find_element(By.ID, "btnLogin")
login.click()
admin_menu = driver.find_element_by_id("menu_admin_viewAdminModule")
admin_menu.click()
# Filtro
user_role_dropDown = Select(
    driver.find_element_by_id("searchSystemUser_userType"))
user_role_dropDown.select_by_index('2')
status_dropDown = Select(driver.find_element_by_id("searchSystemUser_status"))
status_dropDown.select_by_value('1')
#Esta función casi no se utiliza
#status_dropDown.select_by_visible_text("Enable")
search_btn = driver.find_element_by_id("searchBtn")
search_btn.click()
Beispiel #47
0
    def testMethod(self):
        # os.getcwd() will fetch the current working directory
        browser = input("Select the browser FF or CH \n")
        driver = None
        # FireFox browser
        if browser == "FF":
            gekodriverpath = os.getcwd() + "/Drivers/geckodriver.exe"
            driver = webdriver.Firefox(executable_path=gekodriverpath)
        # Chrome browser
        elif browser == "CH":
            chromedriverpath = os.getcwd() + "/Drivers/chromedriver.exe"
            driver = webdriver.Chrome(executable_path=chromedriverpath)
        # initiating web-driver instance

        try:
            driver.implicitly_wait(10)
            driver.maximize_window()
            driver.get("https://learn.letskodeit.com/p/practice")

            # this is javascript execution
            # driver.execute_script("window.location = 'https://www.google.com';")  # to open the web-page.
            # driver.execute_script("return document.getElementById("ID")")  # finding element using java script
            # driver.execute_script("window.scrollBy(0,1000);")  # to scroll down using java script
            # driver.execute_script("window.scrollBy(0,-1000);")  # to scroll down using java script

            # Getting size of window using javascript
            height = driver.execute_script("return window.innerHeight;")
            width = driver.execute_script("return window.innerWidth;")
            print("height is %d" % height)
            print("width is %d" % width)

            driver.find_element_by_id("bmwradio").click()
            # web-element state
            print(driver.find_element_by_id("bmwradio").is_displayed())
            print(driver.find_element_by_id("bmwradio").is_enabled())
            print(driver.find_element_by_id("bmwradio").is_selected())
            # Radio Button Example
            driver.find_element(By.ID, "bmwradio").click(
            )  # this will also work but it is just an example.
            # list of radio buttons being fetched in the below command.
            RadioButtonList = driver.find_elements_by_xpath(
                "//fieldset/label/input[@type='radio']")
            for btn in RadioButtonList:
                btn.click()  # Clicking the radio button in loop
                print(btn.get_attribute("value"))

            # Select Class Example
            dropdownList = driver.find_element_by_xpath(
                "//fieldset/select[@id='carselect']")
            select = Select(dropdownList)
            for opt in select.options:
                if opt.text == "Honda":
                    select.select_by_visible_text(opt.text)

            for index in range(len(select.options)):
                select.select_by_index(index)

            # Select class with multi select
            multidropdownList = driver.find_element_by_xpath(
                "//fieldset/select[@id='multiple-select-example']")
            select = Select(multidropdownList)

            # multi select
            for opt in select.options:
                select.select_by_visible_text(opt.text)

            # Checkbox Example
            checkboxList = driver.find_elements_by_xpath(
                "//input[@type='checkbox']")
            for checkbox in checkboxList:
                checkbox.click()

            # switch tab Example (Same logic as switch-to window)
            currenttab = driver.window_handles[0]
            driver.find_element_by_id("opentab").click()
            time.sleep(1)
            windowHandles = driver.window_handles
            for x in range(len(windowHandles)):
                if currenttab not in windowHandles[x]:
                    driver.switch_to.window(windowHandles[x])
                    time.sleep(2)
                    driver.find_element_by_id("search-courses").send_keys(
                        "Test2")
                    time.sleep(2)
                    driver.close()
                    driver.switch_to.window(currenttab)
                    time.sleep(2)

            # Switch Window Example
            baseWindow = driver.window_handles[0]
            driver.find_element_by_id("openwindow").click()
            size = len(driver.window_handles)
            for win in range(size):
                if baseWindow not in driver.window_handles[win]:
                    driver.switch_to.window(driver.window_handles[win])
                    time.sleep(2)
                    driver.find_element_by_id("search-courses").send_keys(
                        "Test1")
                    time.sleep(2)
                    driver.close()
                    time.sleep(2)
                    driver.switch_to.window(baseWindow)

            # Switch-to alert Example
            time.sleep(1)
            driver.find_element_by_name("enter-name").send_keys("Hello World")
            time.sleep(2)
            driver.find_element_by_css_selector(
                "input[value^='Alert']").click()
            time.sleep(1)
            wait = WebDriverWait(driver, 10)
            wait.until(expected_conditions.alert_is_present())
            AlertPrompt = driver.switch_to.alert
            print("Data fetched from Alert is : " + AlertPrompt.text)
            AlertPrompt.accept()
            time.sleep(2)

            # keyboard Actions. Pressing page down
            #keyboard.send_keys("{PGDN}")
            #keyboard.send_keys("{PGDN}")

            # I-frame Example
            iframewindow = driver.find_element(By.ID, "courses-iframe")
            driver.switch_to.frame(iframewindow)
            time.sleep(2)
            driver.find_element(By.ID, "search-courses").send_keys("python")
            time.sleep(3)
            driver.switch_to.default_content()

            # keyboard Actions. Pressing page up
            #keyboard.send_keys("{PGUP}")

            # Element Displayed Example
            driver.find_element(By.ID, "show-textbox").click()
            time.sleep(3)
            driver.find_element(By.ID,
                                "displayed-text").send_keys("Hello World")

            # taking screenshots
            driver.get_screenshot_as_file(os.getcwd() +
                                          "/ScreenShots/test1.png")

        except Exception as e:
            print("Exception occurred : " + str(e))

        finally:
            print("Closing the current browser")
            driver.close()
def create_nike(n, location, PROXY=False):
    n = n - 1
    r_mail = ''.join(
        random.choice(string.ascii_letters + string.digits)
        for i in range(8)) + '@gmail.com'
    r_fn = ''.join(random.choice(string.ascii_letters) for i in range(4))
    r_pas = ''.join(
        random.choice(string.digits + string.ascii_lowercase +
                      string.ascii_uppercase + string.digits)
        for i in range(12))
    r_ln = ''.join(random.choice(string.ascii_letters) for i in range(4))

    if PROXY == True:
        chrome_options.add_argument('--proxy-server=http://%s' % proxiess[n])
        print("Connected to proxy -> {}".format(proxiess[n]))

    else:
        print("Using without proxy.")

    driver = webdriver.Chrome(chrome_options=chrome_options,
                              executable_path=chromedriver_location)

    if PROXY == True:
        print("Connected to proxy -> {}".format(proxiess[n]))

    print("Starting new session...")

    if location == 'CN2':

        os.system("cls")
        username = input("Input username for smscin... ")
        os.system("cls")
        token = input("Input token for smscin... ")
        os.system("cls")
        pid = input("Input pid for smscin... ")

        driver.get('https://www.nike.com/cn/zh_cn/s/register')

        try:
            time.sleep(4)
            try:
                flag = driver.find_element_by_xpath(
                    "//div[@class='modal-close-glyph nsg-glyph--x']")
                flag.click()
            except:
                print("Something went wrong:/")
            input_num = driver.find_element_by_xpath("//input[@type='tel']")
            input_num.click()
            input_num.clear()
            input.send_keys(VerSMS.getmobile_cn(token, username, pid))
            print("Number -> {}".format(
                VeySMS.getmobile_cn(token, username, pid)))

            time.sleep(2)

            send_code = driver.find_element_by_xpath(
                "//input[@value='Send Code']")
            send_code.click()

            time.sleep(15)

            code = driver.find_element_by_xpath("//input[@value='number']")
            code.click()
            code.clear()
            code.send_keys(VerSMS.getsms_cn(token, username, pid))
            print("Code -> {}".format(VerSMS.getsms_cn(token, username, pid)))

            time.sleep(1)

        except Exception as e:
            print(e)

    else:

        try:
            if location == 'US':
                driver.get('https://www.nike.com/us/en_us/s/register')
            if location == 'UK':
                driver.get('https://www.nike.com/gb/en_gb/s/register')

        except Exception as e:

            print(e)

        time.sleep(5)
        '''if driver.find_element_by_class_name('exp-geodetect-notifier__title nsg-font-family--platform').is_displayed():
            flag = driver.find_element_by_class_name('exp-geodetect-notifier__flag')
            flag.click()'''

        try:
            flag = driver.find_element_by_xpath(
                "//div[@class='modal-close-glyph nsg-glyph--x']")
            flag.click()
        except:
            print("Something went wrong:/")

        time.sleep(4)

        try:

            try:
                em = driver.find_element_by_name('emailAddress')
                em.click()
            except:
                print("Couldn't click!")
            time.sleep(1)
            em.clear()

            em.send_keys(r_mail)

            time.sleep(2)

            try:
                pas = driver.find_element_by_name('password')
                pas.click()
            except:
                print("Couldn't click!")
            time.sleep(1)
            pas.clear()
            try:
                pas.send_keys(r_pas)
            except:
                print("Couldn't send keys!")

            time.sleep(2)

            try:
                fn = driver.find_element_by_name('firstName')
                fn.click()
            except:
                print("Couldn't click!")
            time.sleep(1)
            fn.clear()
            try:

                fn.send_keys(r_fn)
            except:
                print("Couldn't send keys!")

            time.sleep(2)

            try:
                ln = driver.find_element_by_name('lastName')
                ln.click()
            except:
                print("Couldn't click!")
            time.sleep(1)
            ln.clear()
            try:

                ln.send_keys(r_ln)
            except:
                print("Couldn't send keys!")

            time.sleep(2)

            try:
                date_mm = Select(
                    driver.find_element_by_id('nike-unite-date-id-mm'))
                for index in range(len(date_mm.options)):
                    date_mm = Select(
                        driver.find_element_by_id('nike-unite-date-id-mm'))
                    date_mm.select_by_index(index)
                time.sleep(2)

                date_dd = Select(
                    driver.find_element_by_id('nike-unite-date-id-dd'))
                for index in range(len(date_dd.options)):
                    date_dd = Select(
                        driver.find_element_by_id('nike-unite-date-id-dd'))
                    date_dd.select_by_index(index)
                time.sleep(2)

                date_yyyy = Select(
                    driver.find_element_by_id('nike-unite-date-id-yyyy'))
                for index in range(len(date_yyyy.options)):
                    date_yyyy = Select(
                        driver.find_element_by_id('nike-unite-date-id-yyyy'))
                    date_yyyy.select_by_index(index)
                time.sleep(2)

            except:
                date_mm = driver.find_element_by_name('dateOfBirth')
                date_mm.clear()
                date_mm.send_keys('01.01.2000')

            try:
                genre = driver.find_element_by_xpath(
                    "//span[contains(text(), 'Male')]")
                genre.click()
            except:
                print("Couldn't click!")

            time.sleep(2)

            try:
                login_btn = driver.find_element_by_xpath(
                    "//input[@value='CREATE ACCOUNT']")
                login_btn.click()
                time.sleep(2)
                print(" >>> Account created!")
                write_file(r_mail, r_pas)
            except:
                print("Couldn't click!")

            time.sleep(1)

            driver.quit()

        except Exception as e:

            print(e)
Beispiel #49
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
import time

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome("/Users/RSUH/drivers/chromedriver",
                          chrome_options=chrome_options)
driver.get('https://www.rsuh.ru/raspis/')

srok = Select(driver.find_element_by_name('srok'))
srok.select_by_index(1)

driver.find_element_by_id("filters").click()

caf = Select(driver.find_element_by_name('caf'))
caf.select_by_index(62)

driver.find_element_by_name('potokbut2').click()

soup = BeautifulSoup(driver.page_source)

data = []
table = soup.find('table', attrs={'cellpadding': '3', 'border': '0'})
table_body = table.find('tbody')

rows = table_body.find_all('tr')
Beispiel #50
0
driver.get(url)
time.sleep(2)
UsernameTextBox = driver.find_element_by_xpath("//*[@id='user_login']")
UsernameTextBox.send_keys(username)

UserPassWord = driver.find_element_by_xpath("//*[@id='user_pass']")
UserPassWord.send_keys(userpassword)

LoginButton = driver.find_element_by_xpath("//*[@id='wp-submit']")
LoginButton.click()
time.sleep(3)

# Message Type
MessageTypeDropDown = Select(driver.find_element_by_xpath("//*[@id='message']"))
# MessageTypeDropDown.select_by_value("refill")
MessageTypeDropDown.select_by_index(1)

# Prescription Number
PrescriptionText = driver.find_element_by_xpath("//*[@id='serial_number']")
PrescriptionText.send_keys(presc)
# driver.close()

# Pharmacy Information
pharmacyDropDown = Select(driver.find_element_by_xpath("//*[@id='pharmacy']"))
pharmacyDropDown.select_by_index(2)

# Provider Information
providerFirstName = driver.find_element_by_xpath("//*[@id='prov_fname']").send_keys(os.getenv("PROVFIRSTNAME"))
providerLastName = driver.find_element_by_xpath("//*[@id='prov_lname']").send_keys(os.getenv("PROVLASTNAME"))
providerNPI = driver.find_element_by_xpath("//*[@id='prov_npi']").send_keys(os.getenv("NPI"))
providerSPI = driver.find_element_by_xpath("//*[@id='SPI']").send_keys(os.getenv("SPI"))
Beispiel #51
0
print("存放位置:" + os.getcwd() + "/tree_data")
#開啟chrome driver
driver.get(tree_list_url)

s1 = Select(driver.find_element_by_name('menu'))
length = len(s1.options)

#列出老樹網址列表
path = "./tree_data"  #建立資料夾
if not os.path.isdir(path):
    os.mkdir(path)
rows = list()
bar = ChargingBar('抓取樹木清單', max=length, suffix='%(percent)d%%')
for i in range(1, length):
    s1 = Select(driver.find_element_by_name('menu'))
    s1.select_by_index(i)
    soup = BeautifulSoup(driver.page_source, "html.parser")
    a_tags = soup.select('td')
    table = soup.find('table', {'cellspacing': '0'})  #找到表格
    trs = table.find_all('tr')[1:]  #取出元素
    for tr in trs:
        temp = [
            td.text.replace('\n', '').replace('\xa0', '').replace('\t', '')
            for td in tr.find_all('td')
        ]  #取出內容
        url = [a.get('href') for a in tr.find_all('a')]  #獨立出網址
        temp.append(url[0])
        rows.append(temp)
    bar.next()
rows = np.array(rows)
rows = np.delete(rows, [3], axis=1)
Selecciona el elemento con el índice 0
Selecciona el elemento con el texto Auto
"""
import sys
from solutions.module_11.webdriver_factory import create_driver_instance
from selenium.webdriver.support.ui import Select

# Create driver instance
driver = create_driver_instance('chrome')
driver.implicitly_wait(3)
driver.get('https://www.amazon.com.mx/')

dropdown = Select(driver.find_element_by_id('searchDropdownBox'))

print('*' * 80)
print('Dropdown options')
# List - [WebElement, WebElement, WebElement]
for index, option in enumerate(dropdown.options):
    print(f'\t{index}: {option.text}')

print('*' * 80)
print(f'Multiple: {dropdown.is_multiple}')

print('*' * 80)
print(f'First selected option: {dropdown.first_selected_option.text}')

dropdown.select_by_index(0)
dropdown.select_by_visible_text('Auto')

driver.quit()
Beispiel #53
0
def _form_fill_and_submit(form, user_info, webdriver, clear, browser_params,
                          manager_params, screenshot_filename):
    """Fills out a form and submits it, then waits for the response."""
    # try to fill all input fields in the form...
    input_fields = form.find_elements_by_tag_name('input')
    submit_button = None
    text_field = None
    for input_field in input_fields:
        if not input_field.is_displayed():
            continue

        type = input_field.get_attribute('type').lower()
        if type == 'email':
            # using html5 "email" type, this is probably an email field
            _type_in_field(input_field, user_info['email'], clear)
            text_field = input_field
        elif type == 'text':
            # try to decipher this based on field attributes
            if _element_contains_text(input_field, 'company'):
                _type_in_field(input_field, user_info['company'], clear)
            elif _element_contains_text(input_field, 'title'):
                _type_in_field(input_field, user_info['title'], clear)
            elif _element_contains_text(input_field, 'name'):
                if _element_contains_text(input_field,
                                          ['first', 'forename', 'fname']):
                    _type_in_field(input_field, user_info['first_name'], clear)
                elif _element_contains_text(input_field,
                                            ['last', 'surname', 'lname']):
                    _type_in_field(input_field, user_info['last_name'], clear)
                elif _element_contains_text(input_field, ['user', 'account']):
                    _type_in_field(input_field, user_info['user'], clear)
                else:
                    _type_in_field(input_field, user_info['full_name'], clear)
            elif _element_contains_text(input_field, ['zip', 'postal']):
                _type_in_field(input_field, user_info['zip'], clear)
            elif _element_contains_text(input_field, 'city'):
                _type_in_field(input_field, user_info['city'], clear)
            elif _element_contains_text(input_field, 'state'):
                _type_in_field(input_field, user_info['state'], clear)
            elif _element_contains_text(input_field, _KEYWORDS_EMAIL):
                _type_in_field(input_field, user_info['email'], clear)
            elif _element_contains_text(input_field, ['street', 'address']):
                if _element_contains_text(input_field, ['2', 'number']):
                    _type_in_field(input_field, user_info['street2'], clear)
                elif _element_contains_text(input_field, '3'):
                    pass
                else:
                    _type_in_field(input_field, user_info['street1'], clear)
            elif _element_contains_text(input_field,
                                        ['phone', 'tel', 'mobile']):
                _type_in_field(input_field, user_info['tel'], clear)
            elif _element_contains_text(input_field, 'search'):
                pass
            else:
                # skip if visibly marked "optional"
                placeholder = input_field.get_attribute('placeholder')
                if placeholder is not None and 'optional' in placeholder.lower(
                ):
                    pass

                # default: assume email
                else:
                    _type_in_field(input_field, user_info['email'], clear)
            text_field = input_field
        elif type == 'number':
            if _element_contains_text(input_field, ['phone', 'tel', 'mobile']):
                _type_in_field(input_field, user_info['tel'], clear)
            elif _element_contains_text(input_field, ['zip', 'postal']):
                _type_in_field(input_field, user_info['zip'], clear)
            else:
                _type_in_field(input_field, user_info['zip'], clear)
        elif type == 'checkbox' or type == 'radio':
            # check anything/everything
            if not input_field.is_selected():
                input_field.click()
        elif type == 'password':
            _type_in_field(input_field, user_info['password'], clear)
        elif type == 'tel':
            _type_in_field(input_field, user_info['tel'], clear)
        elif type == 'submit' or type == 'button' or type == 'image':
            if _element_contains_text(input_field, _KEYWORDS_SUBMIT):
                submit_button = input_field
        elif type == 'reset' or type == 'hidden' or type == 'search':
            # common irrelevant input types
            pass
        else:
            # default: assume email
            _type_in_field(input_field, user_info['email'], clear)

    # find 'button' tags (if necessary)
    if submit_button is None:
        buttons = form.find_elements_by_tag_name('button')
        for button in buttons:
            if not button.is_displayed():
                continue

            # filter out non-submit button types
            type = button.get_attribute('type').lower()
            if type is not None and (type == 'reset' or type == 'menu'):
                continue

            # pick first matching button
            if _element_contains_text(button, _KEYWORDS_SUBMIT):
                submit_button = button
                break

    # fill in 'select' fields
    select_fields = form.find_elements_by_tag_name('select')
    for select_field in select_fields:
        if not select_field.is_displayed():
            continue

        # select an appropriate element if possible,
        # otherwise second element (to skip blank fields),
        # falling back on the first
        select = Select(select_field)
        select_options = select.options
        selected_index = None
        for i, opt in enumerate(select_options):
            opt_text = opt.text.strip().lower()
            if opt_text in _KEYWORDS_SELECT:
                selected_index = i
                break
        if selected_index is None:
            selected_index = min(1, len(select_options) - 1)
        select.select_by_index(selected_index)

    # debug: save screenshot
    # FIXME: if you want, you can put logic here to save screenshot of filled forms
    # if screenshot_filename: save_screenshot(screenshot_filename, webdriver, browser_params, manager_params)

    # submit the form
    if submit_button is not None:
        try:
            submit_button.click()  # trigger javascript events if possible
            return
        except:
            pass
    if text_field is not None:
        try:
            text_field.send_keys(Keys.RETURN)  # press enter
        except:
            pass
    try:
        if form.tag_name.lower() == 'form':
            form.submit()  # submit() form
    except:
        pass
    def scrape(self):
        self.driver.get(self.url)

        try:
            self.driver.find_element_by_id(
                'ctl00_ContentPlaceHolder1_btnAccept').click()
        except NoSuchElementException:
            pass

        select = Select(
            self.driver.find_element_by_id(
                'ctl00_ContentPlaceHolder1_drpState'))
        option_indexes = range(1, len(select.options))

        for index in option_indexes[:3]:
            select.select_by_index(index)
            self.driver.find_element_by_id(
                'ctl00_ContentPlaceHolder1_btnSearch').click()

            #
            # Wait for results to finish loading
            #
            wait = WebDriverWait(self.driver, 10)
            wait.until(lambda driver: driver.find_element_by_id(
                'ctl00_ContentPlaceHolder1_uprogressSearchResults').
                       is_displayed() == False)

            pageno = 2

            while True:
                s = BeautifulSoup(self.driver.page_source)
                r1 = re.compile(r'^frmFirmDetails\.aspx\?FirmID=([A-Z0-9-]+)$')
                r2 = re.compile(r'hpFirmName$')
                x = {'href': r1, 'id': r2}

                for a in s.findAll('a', attrs=x):
                    print 'firm name: ', a.text
                    print 'firm url: ', urlparse.urljoin(
                        self.driver.current_url, a['href'])
                    print

                # Pagination
                try:
                    next_page_elem = self.driver.find_element_by_xpath(
                        "//a[text()='%d']" % pageno)
                except NoSuchElementException:
                    break  # no more pages

                print 'page ', pageno, '\n'
                next_page_elem.click()

                def next_page(driver):
                    '''
                    Wait until the next page background color changes indicating
                    that it is now the currently selected page
                    '''
                    style = driver.find_element_by_xpath(
                        "//a[text()='%d']" % pageno).get_attribute('style')
                    return 'background-color' in style

                wait = WebDriverWait(self.driver, 10)
                wait.until(next_page)

                pageno += 1

        self.driver.quit()
Beispiel #55
0
    def select_vehicles(self):

        self.CurrentModule = "select_vehicles"

        ### NOW WE CAN TEST FOR THE ADDING OF VEHCILES ###
        time.sleep(4)

        VehicleYearSelect0 = Select(
            self.driver.find_element_by_xpath("//select[@id='vehicleYear']"))

        YearOption = 0

        while YearOption < len(VehicleYearSelect0.options) - 1:
            try:
                VehicleYearSelect0.select_by_index(YearOption)
            except:
                VehicleYearSelect0 = Select(
                    self.driver.find_element_by_xpath(
                        "//select[@id='vehicleYear']"))
                VehicleYearSelect0.select_by_index(YearOption)

            time.sleep(1)
            VehicleMakeSelect0 = Select(
                self.driver.find_element_by_xpath(
                    "//select[@id='vehicleMake']"))

            MakeOption = 1
            while MakeOption < len(VehicleMakeSelect0.options):
                try:
                    VehicleMakeSelect0.select_by_index(MakeOption)
                except:
                    VehicleMakeSelect0 = Select(
                        self.driver.find_element_by_xpath(
                            "//select[@id='vehicleMake']"))
                    VehicleMakeSelect0.select_by_index(MakeOption)

                time.sleep(1)
                VehicleModelSelect0 = Select(
                    self.driver.find_element_by_xpath(
                        "//select[@id='vehicleModel']"))

                ModelOption = 1
                while ModelOption < len(
                        VehicleModelSelect0.options
                ):  # it really starts to slow down over here
                    try:
                        VehicleModelSelect0.select_by_index(ModelOption)
                    except:
                        VehicleModelSelect0 = Select(
                            self.driver.find_element_by_xpath(
                                "//select[@id='vehicleModel']"))
                        VehicleModelSelect0.select_by_index(ModelOption)

                    # time.sleep(1)
                    ModelOption = ModelOption + 1
                MakeOption = MakeOption + 1
            YearOption = YearOption + 1
from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select

driver= webdriver.Firefox()
driver.get("file:///C:/Users/Bhoomika%20Agarwal/Desktop/Exercise%20Files/CH03/03_02/html_code_03_02.html")

select= Select(driver.find_element_by_name('numReturnSelect'))
select.select_by_index(4)
time.sleep(2)
select.select_by_visible_text("200")
time.sleep(2)
select.select_by_value("250")
time.sleep(2)

options = select.options
print(options)

submit_button = driver.find_element_by_name('continue')
submit_button.submit();
time.sleep(2)

driver.close()
    def test_cascading_filters_on_maps(self):
        driver = self.driver
        # self.email = community_partner_user
        # self.password = community_partner_pwd

        driver.maximize_window()

        driver.get(sta_url + 'communityPartner')
        # Select Menu
        driver.find_element_by_xpath(
            "//IMG[@class='himg']/../../..//I[@class='fa fa-align-justify']"
        ).click()
        # Select All Campus Partners with All Colleges selected
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select A College and check out the campus partners changes
        selectcollege = Select(driver.find_element_by_id('selectCollege'))
        # Select a college
        selectcollege.select_by_index(1)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select another college
        selectcollege.select_by_index(2)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)

        driver.get(sta_url + 'legislativeDistrict')
        # Select Menu
        driver.find_element_by_xpath(
            "//IMG[@class='himg']/../../..//I[@class='fa fa-align-justify']"
        ).click()
        # Select All Campus Partners with All Colleges selected
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select A College and check out the campus partners changes
        selectcollege = Select(driver.find_element_by_id('selectCollege'))
        # Select a college
        selectcollege.select_by_index(1)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select another college
        selectcollege.select_by_index(2)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)

        driver.get(sta_url + 'communityPartnerType')
        # Select Menu
        driver.find_element_by_xpath(
            "//IMG[@class='himg']/../../..//I[@class='fa fa-align-justify']"
        ).click()
        # Select All Campus Partners with All Colleges selected
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select A College and check out the campus partners changes
        selectcollege = Select(driver.find_element_by_id('selectCollege'))
        # Select a college
        selectcollege.select_by_index(1)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select another college
        selectcollege.select_by_index(2)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)

        driver.get(sta_url + 'projectMap')
        # Select Menu
        driver.find_element_by_xpath(
            "//IMG[@class='himg']/../../..//I[@class='fa fa-align-justify']"
        ).click()
        # Select All Campus Partners with All Colleges selected
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select A College and check out the campus partners changes
        selectcollege = Select(driver.find_element_by_id('selectCollege'))
        # Select a college
        selectcollege.select_by_index(1)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
        # Select another college
        selectcollege.select_by_index(2)
        time.sleep(3)
        # Select All Campus Partners to see the campus partners associated with the Colleges
        driver.find_element_by_xpath(
            "//SELECT[@id='selectCollege']/following-sibling::SELECT").click()
        time.sleep(3)
Beispiel #58
0
    def gotoHarmony(self, url, addressToQuote, firstName, lastName,
                    agencyEmail, phoneNumber, effectiveDate, shareName,
                    shareEmail):
        logging.info(
            '################Search Address -- %s #########################' %
            (addressToQuote))
        self.driver.get(url + "search/address")
        product = Select(
            ui.WebDriverWait(self.driver, 15).until(
                EC.visibility_of_element_located((By.ID, "product"))))
        product.select_by_index(1)
        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located((By.ID, "address")))
        element.send_keys(addressToQuote)
        element.send_keys(Keys.RETURN)
        time.sleep(2)

        logging.info(
            '################Click First Address#########################')
        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located(
                (By.CSS_SELECTOR, ".survey-wrapper ul li")))
        element.click()

        logging.info(
            '################Fill Contact Info#########################')
        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located(
                (By.ID, "policyHolders[0].firstName")))
        element.send_keys(firstName)

        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located(
                (By.ID, "policyHolders[0].lastName")))
        element.send_keys(lastName)

        # element = ui.WebDriverWait(self.driver, 15).until(EC.visibility_of_element_located((By.ID, "policyHolders[0].emailAddress")))
        # element.send_keys(agencyEmail)

        # element = ui.WebDriverWait(self.driver, 15).until(EC.visibility_of_element_located((By.ID, "policyHolders[0].primaryPhoneNumber")))
        # element.send_keys(phoneNumber)

        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located((By.ID, "effectiveDate")))
        element.send_keys(effectiveDate)
        try:
            agentCode = Select(
                ui.WebDriverWait(self.driver, 15).until(
                    EC.visibility_of_element_located((By.ID, "agentCode"))))
            # mySelect = Select(self.driver.find_element_by_id("agentCode"))
            agentCode.select_by_index(1)
        except NoSuchElementException:
            try:
                agentCode.select_by_visible_text("WALLY WAGONER")
            except NoSuchElementException:
                element = ui.WebDriverWait(self.driver, 15).until(
                    EC.visibility_of_element_located((By.ID, "agentCode")))
                element.send_keys(Keys.DOWN)

        logging.info(
            '################Submit Contact Info#########################')
        self.driver.find_element_by_css_selector('.btn.btn-primary').click()
        time.sleep(5)

        logging.info(
            '################Fill Underwriting Questions#########################'
        )
        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located(
                (By.ID, "underwritingAnswers.rented.answer")))

        element = self.driver.find_element_by_xpath(
            '//span[@data-test="underwritingAnswers.rented.answer_Never"]')
        self.driver.execute_script("arguments[0].click();", element)

        element = self.driver.find_element_by_xpath(
            '//span[@data-test="underwritingAnswers.previousClaims.answer_No claims ever filed"]'
        )
        self.driver.execute_script("arguments[0].click();", element)

        element = self.driver.find_element_by_xpath(
            '//span[@data-test="underwritingAnswers.monthsOccupied.answer_10+"]'
        )
        self.driver.execute_script("arguments[0].click();", element)

        try:
            element = self.driver.find_element_by_xpath(
                '//span[@data-test="underwritingAnswers.fourPointUpdates.answer_Yes"]'
            )
            self.driver.execute_script("arguments[0].click();", element)
        except NoSuchElementException:
            logging.error(
                '################ Not Found: UW Four Point Updates #########################'
            )

        try:
            element = self.driver.find_element_by_xpath(
                '//span[@data-test="underwritingAnswers.business.answer_No"]')
            self.driver.execute_script("arguments[0].click();", element)
            logging.info(
                '################ UW No Business #########################')
        except NoSuchElementException:
            logging.error('Not Found: UW No Business')

        logging.info(
            '################Submit Underwriting Answers#########################'
        )
        self.driver.find_element_by_css_selector('.btn.btn-primary').click()
        time.sleep(5)

        logging.info(
            '################Submit Coverage Details #########################'
        )
        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located(
                (By.XPATH, '//*[@id="QuoteWorkflow"]/div[13]/div')))
        element.click()
        time.sleep(5)
        self.driver.find_element_by_css_selector('.btn.btn-primary').click()
        time.sleep(5)
        logging.info(
            '################ Click Submit Button Coverage #########################'
        )
        element = ui.WebDriverWait(self.driver, 15).until(
            EC.visibility_of_element_located(
                (By.XPATH, '//*[@id="QuoteWorkflow"]/div[28]/div/button')))
        element.click()
        # time.sleep(5)
        # self.driver.find_element_by_css_selector('.btn.btn-primary').click()
        try:
            logging.info(
                '################ Submit Share Quote Summary #########################'
            )
            element = ui.WebDriverWait(self.driver, 15).until(
                EC.visibility_of_element_located(
                    (By.XPATH, '//*[@id="QuoteWorkflow"]/div[1]/button[2]')))
            element = self.driver.find_element_by_xpath(
                "//form[@id='QuoteWorkflow']/div[1]/button[1]")
            element.click()
            logging.info(
                '################ Click Share Quote Button #########################'
            )
            # time.sleep(5)
            logging.info(
                '################ Fill Share Infor #########################')
            element = ui.WebDriverWait(self.driver, 15).until(
                EC.visibility_of_element_located((By.ID, "toName")))
            element.send_keys(shareName)

            element = ui.WebDriverWait(self.driver, 15).until(
                EC.visibility_of_element_located((By.ID, "toEmail")))
            element.send_keys(shareEmail)

            logging.info(
                '################ Press Enter to Submit #########################'
            )
            buttons = self.driver.find_element_by_xpath(
                "//*[contains(text(), 'Send Email')]")
            logging.info(
                '################ Click Send Email Button ########################'
            )
            buttons.click()
            logging.info(
                '################ Clicked Send Email Button ########################'
            )

            # element = ui.WebDriverWait(self.driver, 15).until(EC.visibility_of_element_located((By.XPATH, '//form[@id="sendQuoteSummary"]/div[2]/button[2]')))
            logging.info(
                '################ Click Send Email Button ########################'
            )
            # element.click()
        except TimeoutException:
            logging.error('Not Found: Share Quote Button', element,
                          addressToQuote)
        except NoSuchElementException:
            logging.error('Not Found: Share Quote Button', element,
                          addressToQuote)
        except:
            logging.error('Error: Share Quote Button', element, addressToQuote)
 def select_option_by_value(self, indexvalue):
     log.info("Selecting option at index:'" + str(indexvalue) +
              "' on element: " + self.id)
     select = Select(self.driver.find_element(self.by, self.id))
     select.select_by_index(indexvalue)
Beispiel #60
0
writer = csv.DictWriter(f, fieldnames=fnames)
writer.writeheader()
l = [
    '12004', '14095', '14645', '12011', '12445', '18101', '12002', '12954',
    '12402', '12554', '12958', '14659', '12461'
]
for i in l:
    browser.implicitly_wait(10)
    elem = browser.find_element_by_name('trainNo').send_keys(i, Keys.RETURN)
    browser.maximize_window()
    browser.implicitly_wait(10)

    select = Select(browser.find_element_by_name('jStation'))
    index = (len(select.options)) - 1

    select.select_by_index(index)
    days = ['jYesterday']
    for day in days:
        try:
            x = WebDriverWait(browser, 20).until(
                EC.element_to_be_clickable(('name', day)))
            x.click()

        except TimeoutException:
            break
        try:
            nodelay = browser.find_element_by_class_name('greenS11L')
            status = nodelay.text
        except:
            delay = browser.find_element_by_css_selector('span.errorTextL11')
            status = delay.text