Пример #1
0
	def Web_Config(self):
		self.pubmodul.location("/html/frameset/frameset/frame[2]")
		config={}
		for i in range (1,29):
			config[i]={}
			if i<=18:
				cf=random.choice(['0A0A0A0A0','1A1A0A0A0','1A0A2A1A0','1A0A3A1A0'])
			elif i>=19 and i<=24:
			    cf=random.choice(['0A0A0A0A0','1A1A0A0A0','1A0A2A1A0','1A0A3A1A0','1A0A4A1A0'])
			else:
				cf=random.choice(['0A0A0A0A0','1A1A0A0A0','1A0A3A1A0','1A0A6A1A0'])
			print cf
			config[i]['configured']=cf
			speed=str("speed_%d"%i)
			select1=Select(self.driver.find_element_by_id(speed))
			select1.select_by_value(cf)
			time.sleep(1)
			
			framesize=random.randint(1518,9600)
			framesize=str(framesize)
			config[i]['max']=framesize
			max=str("max_%d"%i)
			self.driver.find_element_by_id(max).clear()
			self.driver.find_element_by_id(max).send_keys(framesize)
			
			desc=string.join(random.sample('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^*',31)).replace(" ","")
			config[i]['desc']=desc
			name=str("name_%d"%i)
			self.driver.find_element_by_id(name).send_keys(desc)
			time.sleep(1)
		self.driver.find_element_by_xpath("/html/body/form/p/input[2]").click()
		time.sleep(1)
		return config
Пример #2
0
def getHtml(word,driver):

    driver.get('http://www.shufazidian.com')

    elem = driver.find_element_by_name('wd')

    select = Select(driver.find_element_by_name('sort'))
    select.select_by_value('9')
    # print('1, ', ctime())
    elem.send_keys(word)
    # wait = WebDriverWait(driver,5)
    elem.send_keys(Keys.RETURN)
    # driver.implicitly_wait(5)
    # try:
    #     element = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.mbpho')))
    #     print('3, ',ctime())
    # except Exception,e:
    #     print(e)
    # print('4, ', ctime())

    delay = 7 # seconds
    try:
        WebDriverWait(driver, delay).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.mbpho')))
    except TimeoutException:
        # print >>f , "TimeoutException Loading took too much time!"
        pass
    time.sleep(5)

    return driver.page_source
Пример #3
0
    def _select_case(self, role, case):
        """Select the test case.
        """
        # select the case
        elem = Select(self._browser.find_element_by_id('select-dut'))
        elem.select_by_value(str(role))
        time.sleep(1)

        checkbox = None
        wait_until(lambda: self._browser.find_elements_by_css_selector('.tree-node .tree-title') and True)
        elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title')
        finder = re.compile(r'.*\b' + case + r'\b')
        finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b')
        for elem in elems:
            action_chains = ActionChains(self._browser)
            action_chains.move_to_element(elem)
            action_chains.perform()
            logger.debug(elem.text)
            if finder.match(elem.text) or finder_dotted.match(elem.text):
                parent = elem.find_element_by_xpath('..')
                checkbox = parent.find_element_by_class_name('tree-checkbox')
                break

        if not checkbox:
            time.sleep(5)
            raise Exception('Failed to find the case')

        self._browser.execute_script("$('.overview').css('left', '0')")
        checkbox.click()
        time.sleep(1)

        elem = self._browser.find_element_by_id('runTest')
        elem.click()
        if not wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10):
            raise Exception('Failed to start test case')
Пример #4
0
def test_add_new_dataset(driver):
    driver.get("/")

    with create_test_project() as p:
        driver.refresh()
        proj_select = Select(driver.find_element_by_css_selector('[name=project]'))
        proj_select.select_by_value(str(p.id))
        driver.find_element_by_id('react-tabs-2').click()
        driver.find_element_by_partial_link_text('Upload new dataset').click()

        dataset_name = driver.find_element_by_css_selector('[name=datasetName]')
        dataset_name.send_keys(test_dataset_name)

        header_file = driver.find_element_by_css_selector('[name=headerFile]')
        header_file.send_keys(pjoin(os.path.dirname(os.path.dirname(__file__)), 'data',
                                    'asas_training_subset_classes.dat'))

        tar_file = driver.find_element_by_css_selector('[name=tarFile]')
        tar_file.send_keys(pjoin(os.path.dirname(os.path.dirname(__file__)), 'data',
                                 'asas_training_subset.tar.gz'))

        driver.find_element_by_class_name('btn-primary').click()

        driver.implicitly_wait(1)
        status_td = driver.find_element_by_xpath(
            "//div[contains(text(),'Successfully uploaded new dataset')]")
Пример #5
0
def test_delta_scan_live(base_url, selenium):
    """Quickly test a delta scan."""
    selenium.get(base_url)

    new_scan_link = selenium.find_element_by_id('new-scan')
    new_scan_link.click()

    # TODO: Rename field buttons
    collapsed_scanners = selenium.find_element_by_css_selector(
        'a[href*=collapse-deformField2')
    collapsed_scanners.click()
    nmap_options = selenium.find_element_by_name('nmap_options')
    nmap_options.send_keys(PING_SWEEP)
    scanner_a = Select(selenium.find_element_by_name('scanner_a'))
    scanner_a.select_by_value('external')
    scanner_b = Select(selenium.find_element_by_name('scanner_b'))
    scanner_b.select_by_value('dmzscanner')
    scan_target = selenium.find_element_by_name('scan_target')
    scan_target.send_keys('203.0.113.1')
    scan_target.submit()

    time.sleep(5)
    scan_results = selenium.find_element_by_id('external-results').text
    assert '<address addr="203.0.113.1" addrtype="ipv4"/>' not in scan_results
    scan_results = selenium.find_element_by_id('dmzscanner-results').text
    assert '<address addr="203.0.113.1" addrtype="ipv4"/>' in scan_results
Пример #6
0
    def test_new_duplicates_project_name(self):
        """
        Should not be able to create a new project whose name is the same
        as an existing project
       """

        project_name = "dupproject"

        Project.objects.create_project(name=project_name,
                                       release=self.release)

        url = reverse('newproject')
        self.get(url)

        self.enter_text('#new-project-name', project_name)

        select = Select(self.find('#projectversion'))
        select.select_by_value(str(self.release.pk))

        element = self.wait_until_visible('#hint-error-project-name')

        self.assertTrue(("Project names must be unique" in element.text),
                        "Did not find unique project name error message")

        # Try and click it anyway, if it submits we'll have a new project in
        # the db and assert then
        self.click("#create-project-button")

        self.assertTrue(
            (Project.objects.filter(name=project_name).count() == 1),
            "New project not found in database")
Пример #7
0
	def WebConfig(self):
		self.pubmodul.location("/html/frameset/frameset/frame[2]")
		select=Select(self.driver.find_element_by_id("glbl_ena"))
		select.select_by_visible_text("Enabled")
		age=str(random.randint(10,10000000))
		self.driver.find_element_by_id("aging_enabled").click()
		self.driver.find_element_by_id("aging_period").clear()
		self.driver.find_element_by_id("aging_period").send_keys(age)
		config = {}
		config['age']=age
		if self.prjName == 's3280':
			j=9
		if self.prjName == 's4140':
			j=5
		for i in range (1,j):
			config[i]={}
			ena=str("ena_%d"%i)
			select1=Select(self.driver.find_element_by_id(ena))
			select1.select_by_value("1")
			limit_value=str(random.randint(1,1024))

			limit=str("limit_%d"%i)
			config[i]['limit']=limit_value
			self.driver.find_element_by_id(limit).clear()
			self.driver.find_element_by_id(limit).send_keys(limit_value)
			action=str('action_%d'%i)
			action_value=random.choice(['0','1','2','3'])
			config[i]['action']=action_value
			select2=Select(self.driver.find_element_by_id(action))
			select2.select_by_value(action_value)
			time.sleep(1)
		self.driver.find_element_by_xpath("/html/body/form/p/input[2]").click()
		time.sleep(2)
		return config
Пример #8
0
    def persistent_filter_test(self):
        pla = platform_get()
        # go to test page, tab Fragility
        pla.get('/vulnerability/list?type_of_assessment=1')

        # find LLRS dropdown filter menu
        sel_tag = pla.xpath_finduniq(
            "//form[@name='filter']//select[@id='id_llrs']")
        sel = Select(sel_tag)
        sel.select_by_value("LWAL")

        # find filter button and click it
        filter = pla.xpath_finduniq(
            "//form[@name='filter']//button[@type='submit' and"
            " @value='Filter']")
        filter.click()

        # move to tab vulnerability
        pla.get('/vulnerability/list?type_of_assessment=2')
        pla.waituntil_js(10, ("try { return (window.gem_app_initialized"
                              " == true); } catch (exc) { return false; }"))


        # find again LLRS dropdown filter menu
        sel_tag = pla.xpath_finduniq(
            "//form[@name='filter']//select[@id='id_llrs']")
        sel = Select(sel_tag)

        # retrieve the selected item (that must be equal
        # to the previous selected)
        selected_item = sel.all_selected_options

        # check if the value is the same selected in the previous page
        self.assertEqual(selected_item[0].get_attribute('value'), 'LWAL')
Пример #9
0
def select_multi_items(self, select_name):
    """
    Select multiple options from select with label (recommended), name, or
    id. Pass a multiline string of options. e.g.

    .. code-block:: gherkin

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

    select = Select(select_box)
    select.deselect_all()

    for option in option_names:
        try:
            select.select_by_value(option)
        except NoSuchElementException:
            try:
                select.select_by_visible_text(option)
            except NoSuchElementException:
                raise AssertionError("Cannot find option: '{}'.".format(option))
Пример #10
0
 def test(self):
     #Navigate Geico
     self.driver.get('https://Geico.com')
     
     #Choose insurance type and ZIP 
     selection = Select(self.driver.find_element(By.ID, 'insurancetype'))
     selection.select_by_value('motorcycle')
     self.driver.find_element(By.ID, 'zip').send_keys('50840')
     self.driver.find_element(By.ID, 'submitButton').click()
     
     #Fill form 
     self.driver.find_element(By.XPATH, '//*[@class ="radio"][2]').click()
     self.driver.find_element(By.ID, "firstName").send_keys('FirstName')
     self.driver.find_element(By.ID, "lastName").send_keys('LastName')
     self.driver.find_element(By.ID, "street").send_keys('Street Address')
     self.driver.find_element(By.ID, "apt").send_keys('1234')
     self.driver.find_element(By.ID, "zip").clear()
     self.driver.find_element(By.ID, "zip").send_keys('50840')
     self.driver.find_element(By.ID, "date-monthdob").send_keys('01')
     self.driver.find_element(By.ID, "date-daydob").send_keys('25')
     self.driver.find_element(By.ID, "date-yeardob").send_keys('1999')
     selection = Select(self.driver.find_element(By.ID, "hasCycle"))
     selection.select_by_value('N')
     
     #Submit 
     self.driver.find_element(By.ID , 'btnSubmit').submit()
     
     self.driver.close()
     self.driver.quit()
Пример #11
0
 def submit_form(self, form, data, clear=True, submit=True, wait=True):
     for k, v in data.items():
         input_field = form.find_element_by_name(k)
         if input_field.tag_name in ('input', 'textarea'):
             field_type = input_field.get_attribute('type')
             if field_type == 'radio':
                 radio_button = form.find_element_by_css_selector(
                     "input[type=radio][name={}][value='{}']".format(
                         k, v
                     )
                 )
                 radio_button.click()
             elif field_type == 'checkbox':
                 checkbox_button = form.find_element_by_css_selector(
                     'input[type=checkbox][name={}]'.format(k)
                 )
                 if v and not checkbox_button.is_selected():
                     checkbox_button.click()
                 elif not v and checkbox_button.is_selected():
                     checkbox_button.click()
             elif clear and input_field.get_attribute('value'):
                 input_field.clear()
             input_field.send_keys(v)
         elif input_field.tag_name == 'select':
             select_field = Select(input_field)
             select_field.select_by_value(v)
     if submit:
         submit_btn = form.find_element_by_xpath(
             './/button[@type="submit"]')
         submit_btn.click()
     if wait:
         self.wait_for_page_load()
 def fill_address(self):
     try:
         wait = self.wait
         contact_page = self.contact_page
         wait.until(lambda d: contact_page.another_address_button().is_displayed(), message="brak buttona another adress")
         contact_page.another_address_button().click()
         wait.until(lambda d: len(contact_page.address_forms()) > 1)
         for i in range(2):
             contact = self.contact[i]
             wait.until(lambda d: contact_page.street_inputs()[i].is_displayed(), message="pole ulica jest niewidoczne")
             contact_page.street_inputs()[i].send_keys(contact['street'])
             wait.until(lambda d: contact_page.region_inputs()[i].is_displayed(), message="pole wojewodztwo jest niewidoczne")
             contact_page.region_inputs()[i].send_keys(contact['region'])
             wait.until(lambda d: contact_page.postcode_inputs()[i].is_displayed(), message="pole kod pocztowy jest niewidoczne")
             contact_page.postcode_inputs()[i].send_keys(contact['postcode'])
             wait.until(lambda d: contact_page.city_inputs()[i].is_displayed(), message="pole miasto jest niewidoczne")
             contact_page.city_inputs()[i].send_keys(contact['city'])
             wait.until(lambda d: contact_page.country_inputs()[i].is_displayed(), message="pole kraj jest niewidoczne")
             contact_page.country_inputs()[i].send_keys(contact['country'])
             wait.until(lambda d: contact_page.address_dropdown_menues()[i].is_displayed(), 
                 message="menu kategorii adresu nie zostalo wyswietlone")
             select = Select(contact_page.address_dropdown_menues()[i])
             select.select_by_value(contact['type'])
     except Exception:
         pytest.allure.attach(sys._getframe().f_code.co_name, self.driver.get_screenshot_as_png(), type=AttachmentType.PNG)
         raise
Пример #13
0
    def run(self):
        # Load Shabbat TOC and scroll to bottom
        self.load_text_toc("Shabbat").scroll_nav_panel_to_bottom()

        # Check that DL Button is visible and not clickable
        visible = self.driver.execute_script(
            'var butt = $(".downloadButtonInner"); ' +\
            'var butt_bot = butt.offset().top + butt.height(); ' +\
            'var win_height = $(window).height(); ' +\
            'return win_height > butt_bot;'
        )
        assert visible, "Download button below page"
        # This isn't sufficient - it only checks if it's visible in the DOM
        #WebDriverWait(self.driver, TEMPER).until(visibility_of_element_located((By.CSS_SELECTOR, ".downloadButtonInner")))

        WebDriverWait(self.driver, TEMPER).until(invisibility_of_element_located((By.CSS_SELECTOR, '.dlVersionFormatSelect + a')))

        # Select version and format
        s1 = Select(self.driver.find_element_by_css_selector('.dlVersionTitleSelect'))
        s1.select_by_value("Wikisource Talmud Bavli/he")
        s2 = Select(self.driver.find_element_by_css_selector('.dlVersionFormatSelect'))
        s2.select_by_value("csv")

        # Check that DL button is clickable
        WebDriverWait(self.driver, TEMPER).until(visibility_of_element_located((By.CSS_SELECTOR, '.dlVersionFormatSelect + a')))
    def credetials_to_edit_school(self,
                                  driver,
                                  school_name,
                                  address,
                                  xpath_of_school_to_edit,
                                  xpath_of_director):
        """ Function to automate proccess of inserting the credentials """

        driver.find_element_by_xpath(xpath_of_school_to_edit).click()
        input_name_area = driver.find_element_by_xpath(
            self.xpaths['inputSchoolName'])
        input_address_area = driver.find_element_by_xpath(
            self.xpaths['inputSchoolAddress'])
        input_name_area.clear()
        input_name_area.send_keys(school_name)
        input_address_area.clear()
        input_address_area.send_keys(address)

        driver.find_element_by_xpath(
            xpath_of_director).click()

        select = Select(driver.find_element_by_xpath(xpath_of_director))

        select.select_by_value('12')
        driver.find_element_by_xpath(
            self.xpaths['confirmAddEditButton']).click()
Пример #15
0
    def body(self):
        # Load Shabbat TOC and scroll to bottom
        self.nav_to_text_toc(["Talmud"], "Shabbat").scroll_nav_panel_to_bottom()

        # Check that DL Button is visible and not clickable
        visible = self.driver.execute_script(
            'var butt = document.getElementsByClassName("downloadButtonInner")[0]; ' + \
            'var butt_bot = butt.getBoundingClientRect().top + butt.getBoundingClientRect().height; ' + \
            'var win_height = window.innerHeight; ' + \
            'return win_height > butt_bot;'
        )
        assert visible, "Download button below page"
        # This isn't sufficient - it only checks if it's visible in the DOM
        # WebDriverWait(self.driver, TEMPER).until(visibility_of_element_located((By.CSS_SELECTOR, ".downloadButtonInner")))

        WebDriverWait(self.driver, TEMPER).until(
            invisibility_of_element_located((By.CSS_SELECTOR, '.dlVersionFormatSelect + a')))

        # Select version and format
        select1 = Select(self.driver.find_element_by_css_selector('.dlVersionTitleSelect'))
        select1.select_by_value("Wikisource Talmud Bavli/he")
        select2 = Select(self.driver.find_element_by_css_selector('.dlVersionFormatSelect'))
        select2.select_by_value("csv")

        # Check that DL button is clickable
        WebDriverWait(self.driver, TEMPER).until(
            visibility_of_element_located((By.CSS_SELECTOR, '.dlVersionFormatSelect + a')))
Пример #16
0
def test_volvox():
    format_volvox()
    browser = webdriver.Firefox() # Get local session of firefox
    browser.get("file://%s/index.html?data=sample_data/json/volvox" % os.getcwd() ) # Load page

    # select "ctgA from the dropdown
    refseq_selector = Select(browser.find_element_by_id('chrom'))
    refseq_selector.select_by_value('ctgA')

    # check a good browser title
    assert "ctgA" in browser.title, "browser title is actually %s" % browser.title

    tabs = browser.find_elements_by_xpath( '//div[@class="browsingTab"]' )
    for t in tabs:
        t.click()
        time.sleep(1)
        t.click()
        time.sleep(0.5)

    assert_no_js_errors(browser)

    # do a test where we search for a certain gene using the search box
    search_f15(browser)

    assert_no_js_errors(browser)

    # test scrolling, make sure we get no js errors
    scroll(browser)

    # test dragging in and displaying the wiggle track
    wiggle(browser)

    browser.close()
    pass;
Пример #17
0
 def select_term(self, term):
     d = self.driver
     d.get('https://loris.wlu.ca/ssb_prod/bwskflib.P_SelDefTerm')
     dropdown = Select(d.find_element_by_id('term_id'))
     dropdown.select_by_value(term)
     d.find_elements_by_css_selector('form')[1].submit()
     self.term_selected = True
Пример #18
0
 def _run_diff(self, base_build, cand_build):
     browser = self.browser
     browser.get(go_page("generate_diff"))
     
     
     # wait = WebDriverWait(browser, 10)
     # menu = wait.until(EC.element_to_be_selected((By.XPATH,r"/html/body/core-scaffold/core-header-panel/core-menu/core-submenu[2]")))
     # import time 
     # time.sleep(10)
     # menu = browser.find_element_by_xpath(r"/html/body/core-scaffold/core-header-panel/core-menu/core-submenu[2]")
     # menu.click()
     # sub_menu = wait.until(EC.element_to_be_clickable((By.XPATH,r"/html/body/core-scaffold/core-header-panel/core-menu/core-submenu[2]/core-item[2]/a")))
     # sub_menu.click()
     
     # browser.switch_to_frame(browser.find_element_by_tag_name("iframe"))
     
     
     base = Select(browser.find_element_by_id("deformField1"))
     cand = Select(browser.find_element_by_id("deformField2"))
     # base_build = get_build(base.options, base_build) 
     # cand_build = get_build(cand.options, base_build)
     try:
         base.select_by_value(base_build)
         cand.select_by_value(cand_build)
     except:
         raise Exception("wrong build name")
     
     browser.find_element_by_id("deformsubmit").click()
Пример #19
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)
Пример #20
0
def test_cannot_compute_zero_features(driver, project, dataset):
    driver.get('/')
    driver.refresh()
    proj_select = Select(driver.find_element_by_css_selector('[name=project]'))
    proj_select.select_by_value(str(project.id))

    driver.find_element_by_id('react-tabs-4').click()
    driver.find_element_by_partial_link_text('Compute New Features').click()
    driver.find_element_by_xpath("//li[contains(text(),'General')]").click()

    amplitude = driver.find_element_by_css_selector('[name=amplitude]')
    assert amplitude.get_attribute('value') == 'true'
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    time.sleep(0.1)
    assert amplitude.get_attribute('value') == 'false'

    driver.find_element_by_xpath("//li[contains(.,'Cadence')]").click()
    n_epochs = driver.find_element_by_css_selector('[name=n_epochs]')
    assert n_epochs.get_attribute('value') == 'true'
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    time.sleep(0.1)
    assert n_epochs.get_attribute('value') == 'false'

    driver.find_element_by_xpath("//li[contains(.,'Lomb-Scargle')]").click()
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    assert driver.find_element_by_css_selector(
        '[name=fold2P_slope_10percentile]').get_attribute('value') == 'false'

    featureset_name = driver.find_element_by_css_selector('[name=featuresetName]')
    featureset_name.send_keys(test_featureset_name)

    driver.find_element_by_class_name('btn-primary').click()

    driver.wait_for_xpath(
        "//div[contains(.,'At least one feature must be selected')]")
Пример #21
0
def test_check_uncheck_features(driver, project, dataset):
    driver.get('/')
    driver.refresh()
    proj_select = Select(driver.find_element_by_css_selector('[name=project]'))
    proj_select.select_by_value(str(project.id))

    driver.find_element_by_id('react-tabs-4').click()
    driver.find_element_by_partial_link_text('Compute New Features').click()
    driver.find_element_by_xpath("//li[contains(text(),'General')]").click()

    amplitude = driver.find_element_by_css_selector('[name=amplitude]')
    assert amplitude.get_attribute('value') == 'true'
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    time.sleep(0.3)
    assert amplitude.get_attribute('value') == 'false'
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    time.sleep(0.1)
    assert amplitude.get_attribute('value') == 'true'

    driver.find_element_by_xpath("//li[contains(.,'Cadence')]").click()
    n_epochs = driver.find_element_by_css_selector('[name=n_epochs]')
    assert n_epochs.get_attribute('value') == 'true'
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    time.sleep(0.1)
    assert n_epochs.get_attribute('value') == 'false'

    driver.find_element_by_xpath("//li[contains(.,'Lomb-Scargle')]").click()
    driver.find_element_by_partial_link_text('Check/Uncheck All').click()
    assert driver.find_element_by_css_selector(
        '[name=fold2P_slope_10percentile]').get_attribute('value') == 'false'
Пример #22
0
 def batch(key, match_file):
     workflow.webbrowser("https://www.ncbi.nlm.nih.gov/sites/batchentrez");
     
     element1 = driver.find_element_by_name("file");
     element1.send_keys(key + "/" + match_file)
     element2 = Select(driver.find_element_by_name("db"));
     element2.select_by_value("protein");
Пример #23
0
    def select(self, option=None, value=None, name=None, id=None, xpath=None, css=None):
        how = None
        what = None
        selector = None
        if name:
            what = name
            how = By.NAME
            selector = 'name'
        elif id:
            what = id
            how = By.ID
            selector = 'id'
        elif xpath:
            what = xpath
            how = By.XPATH
            selector = 'xpath'
        elif css:
            what = css
            how = By.CSS_SELECTOR
            selector = 'css'
        else:
            raise ValueError("No valid selector passed (name, id, xpath or css)")

        elem = self.find_element(by=how, value=what)
        select = Select(elem)
        if value:
            print "SELECT value = " + value + " IN " + selector + " = " + what
            select.select_by_value(value)
        elif option:
            print "SELECT option = " + str(option) + " IN " + selector + " = " + what
            select.select_by_visible_text(option)
        else:
            raise ValueError("No option or value passed")
Пример #24
0
 def engineConfigLog(self,srvaddr):
         print "\n========engineConfig========"
         self.PubModuleEle.location("/html/frameset/frameset/frame[1]")
         time.sleep(2)
         self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td/ul/li/a").click()# locate Configuration
         time.sleep(2)
         self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td/ul/li/div/ul/li/a").click()#locate System
         time.sleep(2)
         self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td/ul/li/div/ul/li/div/ul/li[6]/a").click()# locate log
         time.sleep(2)
         print "***********ConfigurationFinish*************"
         self.PubModuleEle.location("/html/frameset/frameset/frame[2]")
         time.sleep(2)
         WebDriverWait(self.driver, 30).until(lambda driver :driver.find_element_by_name("server_mode"))
         select = Select(self.driver.find_element_by_name("server_mode"))
         select.select_by_value("1")
         elem=self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td[2]/input")
         elem.clear()
         self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td[2]/input").send_keys(srvaddr)
         s1=self.driver.find_element_by_name("server_addr").get_attribute("value")
         print "the serveraddr is %s"%s1
         WebDriverWait(self.driver, 30).until(lambda driver :driver.find_element_by_name("syslog_level"))
         select = Select(self.driver.find_element_by_name("syslog_level"))
         select.select_by_value("0")
         self.driver.find_element_by_xpath( "/html/body/form/p/input").click()
Пример #25
0
def _select(browser, text, index=0):
    def is_clickable(browser):
        elems = browser.find_elements_by_css_selector('.celltoolbar select')
        if len(elems) <= index:
            return False
        elem = elems[index]
        return elem.is_displayed and elem.is_enabled

    def is_option(browser):
        elem = browser.find_elements_by_css_selector('.celltoolbar select')[index]
        select = Select(elem)
        options = [x.get_attribute('value') for x in select.options]
        return text in options

    _wait(browser).until(is_clickable)
    _wait(browser).until(is_option)
    elem = browser.find_elements_by_css_selector('.celltoolbar select')[index]
    select = Select(elem)
    select.select_by_value(text)

    def selected(browser):
        elem = browser.find_elements_by_css_selector('.celltoolbar select')[index]
        return elem.get_attribute('value') == text

    _wait(browser).until(selected)
Пример #26
0
	def login(driver, user, passwd,app_key):
		driver.get('https://login.taobao.com/member/login.jhtml?redirectURL=http://clouddata.taobao.com/ide/data.htm?spm=0.0.0.0.Zrhz8L&sub=true')
		print driver.title.encode('utf-8')
		driver.execute_script("document.querySelector('#J_SafeLoginCheck').click();")
		# driver.find_element_by_id('J_SafeLoginCheck').click()
		driver.execute_script("document.querySelector('#TPL_username_1').value= '%s';" % user)
		driver.execute_script("document.querySelector('#TPL_password_1').value= '%s';" % passwd)
		driver.execute_script("document.querySelector('#J_SubmitStatic').click();")

		# driver.find_element_by_id('TPL_username_1').send_keys(user)
		# driver.find_element_by_id('TPL_password_1').send_keys(passwd)
		# driver.find_element_by_id('J_SubmitStatic').click()
		
		wait = ui.WebDriverWait(driver, 30)
		wait.until(lambda driver:driver.find_element_by_css_selector("#settings > div.w_con > div > form > table > tbody > tr:nth-child(3) > td:nth-child(2) > input:nth-child(1)").is_displayed())

		print driver.title.encode('utf-8')
		if app_key is None or not app_key.strip():
			return
		print "app_key: %s" % app_key
		if(u'聚石塔数据引擎 - 用户设置' in driver.title):
			#选择合适的app_key
			select=Select(driver.execute_script("return document.querySelector('#J_app_list')"))
			# select.find_element_by_xpath("//option[@value='%s']" % app_key).click()
			select.select_by_value(app_key)
			driver.find_element_by_css_selector("#settings > div.w_con > div > form > table > tbody > tr:nth-child(3) > td:nth-child(2) > input:nth-child(1)").click()
Пример #27
0
 def parse(self, response):
     self.br.get(response.url)
     username=self.br.find_element_by_id('dnn_ctr3337_View_ctl00_tbUserName')
     username.send_keys(USERNAME)
     pwd=self.br.find_element_by_id('dnn_ctr3337_View_ctl00_tbPassword')
     pwd.send_keys(PASSWORD)
     sub=self.br.find_element_by_id('dnn_ctr3337_View_ctl00_btnSignIn')
     sub.click()
     time.sleep(1)
     el=self.br.find_element_by_id('dnn_ctr4356_ViewJobBank_Candidate_lb_JobSearch')
     el.click()
     time.sleep(1)
     subfield=Select(self.br.find_element_by_id('dnn_ctr4356_ViewJobBank_JobSearch_dl_Subfield'))
     subfield.select_by_value(SUBFIELD)
     el=self.br.find_element_by_id('dnn_ctr4356_ViewJobBank_JobSearch_btn_Submit')
     el.click()
     time.sleep(1)    
     # loop over pages
     hxs=Selector(text=self.br.page_source,type='html')
     pages=hxs.xpath('//td[contains(@class,"rgPagerCell")]//div[contains(@class,"rgNumPart")]//a/@href')
     for idx in range(1,len(pages)+1):
         page_link=self.br.find_element_by_xpath('//td[contains(@class,"rgPagerCell")]//div[contains(@class,"rgNumPart")]//a[%s]'%idx)
         page_link.click()
         time.sleep(3)
         hxs=Selector(text=self.br.page_source,type='html')
         rows=hxs.xpath('//table[@class="rgMasterTable"]/tbody/tr')
         outframe=[{"link":i.xpath("td[2]//a/@href").extract()[0],
                    "date":str(i.xpath("td[6]//text()").extract()[0])}
                    for i in rows]
         for idx,i in enumerate(outframe):#enumerate(out[0:3]): # for testing
             request=scrapy.Request(outframe[idx]['link'],self.after_parse)
             request.meta['post_date']=outframe[idx]['date']
             logging.debug("requesting: %s"%request.url)
             yield request
Пример #28
0
def _click_download(proj_id, driver):
    driver.refresh()
    proj_select = Select(driver.find_element_by_css_selector('[name=project]'))
    proj_select.select_by_value(str(proj_id))
    driver.find_element_by_id('react-tabs-8').click()
    driver.wait_for_xpath("//a[text()='Download']").click()
    time.sleep(0.5)
Пример #29
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)
Пример #30
0
    def _select_case(self, suite, case):
        """Select the test case.
        """
        # select the case
        elem = Select(self._browser.find_element_by_id('select-dut'))
        elem.select_by_value(str(suite))
        time.sleep(1)

        checkbox = None
        elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title')
        for elem in elems:
            action_chains = ActionChains(self._browser)
            action_chains.move_to_element(elem)
            action_chains.perform()
            logger.debug(elem.text)
            if elem.text.startswith(case):
                parent = elem.find_element_by_xpath('..')
                checkbox = parent.find_element_by_class_name('tree-checkbox')
                break

        if not checkbox:
            time.sleep(5)
            raise Exception('Failed to find the case')

        checkbox.click()
        time.sleep(1)

        elem = self._browser.find_element_by_id('runTest')
        elem.click()
        if not self.wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10):
            raise Exception('Failed to start test case')
Пример #31
0
 def _select_option(self, select_id, option_value):
     select = Select(self.browser.find_element_by_id(select_id))
     select.select_by_value(option_value)
Пример #32
0
def _select_tests(browser, index=0):
    select = Select(
        browser.find_elements_by_css_selector('.celltoolbar select')[index])
    select.select_by_value('tests')
Пример #33
0
def _select_solution(browser, index=0):
    select = Select(
        browser.find_elements_by_css_selector('.celltoolbar select')[index])
    select.select_by_value('solution')
Пример #34
0
    x = browser.find_element_by_id('treasure')
    value_x = x.get_attribute('valuex')
    print(value_x)

    answer = calc(value_x)
    input_answer = browser.find_element_by_id('answer')
    input_answer.send_keys(answer)
    time.sleep(2)

    robot_chk = browser.find_element_by_id('robotCheckbox')
    robot_chk.click()

    robot_rad_btn = browser.find_element_by_id('robotsRule')
    robot_rad_btn.click()

    button = browser.find_element_by_class_name('btn-default')
    button.click()
    time.sleep(10)

    if False:
        browser.find_element_by_tag_name("select").click()
        browser.find_element_by_css_selector("option:nth-child(2)").click()
        browser.find_element_by_css_selector("[value='1']").click()

        from selenium.webdriver.support.ui import Select
        select = Select(browser.find_element_by_tag_name("select"))
        select.select_by_value("1")  # ищем элемент с текстом "Python"
        # select.select_by_visible_text("text")
        # select.select_by_index(index)
Пример #35
0
#   usernameElem.send_keys('jndiho')
#   passwordElem = browser.find_element_by_name('login_pass')
#   passwordElem.send_keys('NyamoYa89*(')
#   passwordElem.submit()
# except:
#   print('Login to Sonar Failed!')

usernameElem = browser.find_element_by_id('UserUsername')
usernameElem.send_keys('jndiho')
passwordElem = browser.find_element_by_name('login_pass')
passwordElem.send_keys('NyamoYa89*(')
passwordElem.submit()
#Select the New Orders Placed Report from the Report dropdown.
selectReportCategory = Select(browser.find_element_by_id('category_id'))
time.sleep(5)
selectReportCategory.select_by_value('21')
select_report_type = Select(browser.find_element_by_id('report_id'))
time.sleep(5)
select_report_type.select_by_value('242')
time.sleep(5)

#browser.find_element_by_xpath("//input[@name='username']").click()
#Find the csv checkbox and click it
browser.find_element_by_xpath(
    ".//input[@type='checkbox' and @name='report[report_type]']").click()
#Find the "Today" radio button and click it
browser.find_element_by_xpath(
    ".//input[@type='radio' and @value='today']").click()

try:
    #Find the "Generate Report" submit button and click it
Пример #36
0
# инициализируем драйвер браузера. После этой команды вы должны увидеть новое открытое окно браузера
driver = webdriver.Chrome("C:/chromedriver/chromedriver.exe")

# Метод get сообщает браузеру, что нужно открыть сайт по указанной ссылке
driver.get("http://suninjuly.github.io/selects1.html")
time.sleep(1)


def sum(x1, x2):
    return str(int(x1) + int(x2))


# Считываем значение num1 и num2 и подсчитываем их сумму
num1 = driver.find_elements_by_id("num1")[0].text
num2 = driver.find_elements_by_id("num2")[0].text
y = sum(num1, num2)

# Выбираем из выпадающего списка результат суммы
select = Select(driver.find_element_by_tag_name("select"))
select.select_by_value(y)

time.sleep(1)

# Найдем кнопку submit
btnSubmit = driver.find_element_by_css_selector(".btn")
btnSubmit.click()

time.sleep(5)

# После выполнения всех действий мы не должны забыть закрыть окно браузера
driver.quit()
Пример #37
0
select1.select_by_visible_text('2. Patentes Vía Nacional')

'''
<select id="FiltroInicial:desplegableTipoEstadistica" name="FiltroInicial:desplegableTipoEstadistica" class="txt w_320" size="1" onchange="mojarra.ab(this,event,'valueChange',0,'FiltroInicial:desplegableEstadistica FiltroInicial:panelCriterios')"> <option value="">-- seleccione Tipo --</option>
    <option value="3">SOLICITUDES PRESENTADAS</option>
    <option value="4">SOLICITUDES PUBLICADAS</option>
    <option value="5">CONCESIONES</option>
    <option value="6">EN VIGOR</option>
</select>
'''
wait = WebDriverWait(browser,10)
time.sleep(1)
element = wait.until(EC.visibility_of_element_located((By.ID,'FiltroInicial:desplegableTipoEstadistica')))
select2 = Select(browser.find_element_by_id('FiltroInicial:desplegableTipoEstadistica'))
print(select2.options)
select2.select_by_value('6')
'''
<select id="FiltroInicial:desplegableEstadistica" name="FiltroInicial:desplegableEstadistica" class="txt w_540" size="1" onchange="mojarra.ab(this,event,'valueChange',0,'FiltroInicial:panelCriterios')">  <option value="">-- seleccione Estadistica --</option>
    <option value="16">1. Solicitudes de Patentes publicadas por Sectores Técnicos y distribuidas por CC.AA. </option>
    <option value="17">2. Solicitudes de Patentes publicadas por Subsectores Técnicos y distribuidas por provincias</option>
    <option value="18">3. Distribución en porcentaje de los Sectores Técnicos de las solicitudes publicadas de Patentes</option>
    <option value="35">4. Solicitudes de Patentes publicadas por Unidades Técnicas y clases CIP, distribuidas por CC.AA.</option>
    <option value="36">5. Solicitudes de Patentes publicadas por Unidades Técnicas y clases CIP, distribuidas por provincias</option>
</select>
'''
wait = WebDriverWait(browser,10)
time.sleep(1)
select3 = Select(browser.find_element_by_id('FiltroInicial:desplegableEstadistica'))
print(select3.options)
browser.find_element_by_id("FiltroInicial:desplegableEstadistica").click()
wait = WebDriverWait(browser,10)
Пример #38
0
 def select_department(self, title):
     department_selection_element = self.find_element(
         *self.SELECT_DEPARTMENT)
     select = Select(department_selection_element)
     # (the same) select = Select(self.find_element(*self.SELECT_DEPARTMENT)
     select.select_by_value(f'search-alias={title}')
Пример #39
0
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time

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

    x_element = browser.find_element_by_id("num1")
    x = int(x_element.text)
    y_element = browser.find_element_by_id("num2")
    y = int(y_element.text)
    summ = str(x + y)
    select = Select(browser.find_element_by_tag_name("select"))
    select.select_by_value(summ)

    # Отправляем заполненную форму
    button = browser.find_element_by_css_selector("button.btn")
    button.click()

finally:
    # ожидание чтобы визуально оценить результаты прохождения скрипта
    time.sleep(5)
    # закрываем браузер после всех манипуляций
    browser.quit()
Пример #40
0
time.sleep(2)

#ダックシステム
dck = driver.find_element_by_id(
    'ctl00_ContentPlaceHolder1_内訳Syusi12_LinkButton')
dck.click()

#select option(オプションボックス)を丸一日かかって解決した!

optn_element = driver.find_element_by_id(
    'ctl00_ContentPlaceHolder1_対象年月Syusi_DropDownList')
select_element = Select(optn_element)
#mnth=input("対象月入れて(例:2019/03/01)→ ")
#select_element.select_by_value(str(mnth))
#select_element.select_by_value('2019/04/01')#これが正しい!
select_element.select_by_value(DCK_PL_MONTH)  #これが正しい!
#select_element.select_by_value('2018年04月')ではない!!!!!!!!!

time.sleep(2)

#全体
zentai = driver.find_elements_by_css_selector(
    '#ctl00_ContentPlaceHolder1_SyusiMeisai_GridView > tbody > tr:nth-child(51)'
)
rp_z = zentai[0].text
rp_z = rp_z.replace(" ", "/")
print("全 体", rp_z)

#物流
butsuryu = driver.find_elements_by_css_selector(
    '#ctl00_ContentPlaceHolder1_SyusiMeisai_GridView > tbody > tr:nth-child(155)'
Пример #41
0
for single_date in daterange(start_date, end_date):
    print single_date.strftime("%Y-%m-%d")  #gives the proper date format

    #new_dates = base_url.replace("DATE", single_date.strftime("%Y-%m-%d")) #inserts into the DATE of the url
    driver.get(base_url.replace("DATE", single_date.strftime("%Y-%m-%d")))
    #driver.get(new_dates)

    ### A pop-up will appear and suggest for you to close it ###
    close_login = driver.find_element_by_class_name("close-login-alert")
    close_login.click()

    ### we need to gather all players from the drop down...
    ## Use dev tools in chrome; find element name and find value to select...
    # then run code below
    select = Select(driver.find_element_by_name('ff_length'))
    select.select_by_value('-1')

    ### This code "clicks" copy player list - this copies player data to the os clipboard
    elem1 = driver.find_element_by_link_text("copy player list")
    elem1.click()

    ### Closes pop-up that confirms copied player list
    close_copy = driver.find_element_by_class_name(
        "sa-confirm-button-container")
    close_copy.click()

    ### Pandas reads clipboard, converts to DF, then exports to CSV...
    df2 = pd.read_clipboard()
    df2.to_csv(current_directory + single_date.strftime("%Y-%m-%d"))
    #df2.to_csv(single_date.strftime("%Y-%m-%d"), path='/Users/kra7830/NBA_NN_DK/data_folder/')
Пример #42
0
def location_configuration(name, data):
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('sideMenu'))
    tab = browser.find_element_by_id('8')
    tab.click()
    tab.click()
    payroll_prep = browser.find_element_by_link_text('Payroll Prepr.')
    payroll_prep.click()
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    time.sleep(3)
    admin = browser.find_element_by_id('20')
    das = admin.find_elements_by_css_selector('td')
    das[0].click()
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    time.sleep(1)
    loc_con = browser.find_element_by_id('32')
    loc = loc_con.find_elements_by_css_selector('td')
    loc[0].click()
    time.sleep(10)
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    form = browser.find_element_by_name('entLocLaborRuleForm')
    table = form.find_elements_by_class_name('embeddedTable100')
    rest = table[1].find_elements_by_css_selector('li')
    while True:
        try:
            for ele in rest[575:]:
                if ele.text == name:
                    ele.find_element_by_css_selector('input').click()
                    break
                else:
                    continue
        except StaleElementReferenceException:
            break
    time.sleep(6)
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    form = browser.find_element_by_name('entLocLaborRuleForm')
    P_R_check = form.find_element_by_id('entPayRuleUpdated')
    P_R_check.click()
    P_R_data = form.find_element_by_id('entPayRuleEffectiveFrom')
    P_R_data.clear()
    P_R_data.send_keys(data)
    P_R_sel = Select(form.find_element_by_id('entPayRuleID'))
    P_R_sel.select_by_value('276264740')
    save = browser.find_element_by_id('Save')
    save.click()
    time.sleep(6)
    obj = browser.switch_to_alert()
    obj.accept()
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    form = browser.find_element_by_name('entLocLaborRuleForm')
    p_p_check = form.find_element_by_id('payPeriodCalendarUpdated')
    p_p_check.click()
    p_p_data = form.find_element_by_id('payPeriodCalendarEffectiveFrom')
    p_p_data.clear()
    p_p_data.send_keys(data)
    p_p_sel = Select(form.find_element_by_id('payPeriodCalendarID'))
    p_p_sel.select_by_value('276264601')
    save = browser.find_element_by_id('Save')
    save.click()
    time.sleep(10)
    obj = browser.switch_to_alert()
    obj.accept()
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    form = browser.find_element_by_name('entLocLaborRuleForm')
    w_t_check = form.find_element_by_id('entWageTipLawUpdated')
    w_t_check.click()
    w_t_data = form.find_element_by_id('entWageTipLawEffectiveFrom')
    w_t_data.clear()
    w_t_data.send_keys(data)
    w_t_sel = Select(form.find_element_by_id('entWageTipLawID'))
    w_t_sel.select_by_value('2901')
    save = browser.find_element_by_id('Save')
    save.click()
    time.sleep(10)
    obj = browser.switch_to_alert()
    obj.accept()
    browser.switch_to_default_content()
    browser.switch_to.frame(browser.find_element_by_id('myPage'))
    form = browser.find_element_by_name('entLocLaborRuleForm')
    c_l_check = form.find_element_by_id('entChildLaborLawUpdated')
    c_l_check.click()
    c_l_data = form.find_element_by_id('entChildLaborLawEffectiveFrom')
    c_l_data.clear()
    c_l_data.send_keys(data)
    c_l_sel = Select(form.find_element_by_id('entChildLaborLawID'))
    c_l_sel.select_by_value('1034')
    save = browser.find_element_by_id('Save')
    save.click()
    time.sleep(7)
    obj = browser.switch_to_alert()
    obj.accept()
    browser.switch_to_default_content()
Пример #43
0
 def select_size(self):
     elem = Select(
         self.driver.find_element_by_tag_name(self.size_option_tag))
     elem.select_by_value(self.size_option)
Пример #44
0
profile.set_preference(
    'browser.helperApps.neverAsk.saveToDisk',
    "text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream"
)

############## Start Browswer go to database #################
driver = webdriver.Firefox(profile)
#go to the query page
driver.get("http://webapps2.rrc.texas.gov/EWA/uicQueryAction.do")

############## Input Query #################
inputDistrict = Select(
    driver.find_element_by_xpath(
        '/html/body/table[2]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[3]/td[2]/select'
    ))
inputDistrict.select_by_value("10")
driver.find_element_by_xpath(
    '/html/body/table[2]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[4]/td/input[1]'
).click()

############## Download Search Results #################
driver.find_element_by_xpath(
    '/html/body/table[2]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[3]/td/table/tbody/tr/td[1]/input'
).click()

############## Change Search Results to 100 #################
pageSize = Select(
    driver.find_element_by_xpath(
        '/html/body/table[2]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr/td[3]/label/select'
    ))
pageSize.select_by_value('100')
Пример #45
0
from selenium.webdriver.support.ui import Select
from selenium import webdriver
import time

if __name__ == '__main__':
    try:
        page_url = 'http://suninjuly.github.io/selects2.html'

        browser = webdriver.Chrome()
        browser.get(page_url)

        x = int(browser.find_element_by_id('num1').text)
        y = int(browser.find_element_by_id('num2').text)
        result = str(x + y)

        select = Select(browser.find_element_by_tag_name('select'))
        select.select_by_value(result)

        btn = browser.find_element_by_class_name('btn')
        btn.click()
    except Exception as e:
        print(e)
    finally:
        time.sleep(15)
        browser.quit()
Пример #46
0
from selenium.webdriver.support.ui import Select

ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
CHROME_PATH = os.path.join(ROOT_DIR, 'drivers', 'chromedriver.exe')

driver = webdriver.Chrome(executable_path=CHROME_PATH)
driver.implicitly_wait(10)

driver.get('https://formsmarts.com/form/axi?mode=h5')

first_name = driver.find_element_by_id('u_wJI_60857')
last_name = driver.find_element_by_id('u_wJI_60858')
email = driver.find_element_by_id('u_wJI_60859')
address = driver.find_element_by_id('u_wJI_60860')
country_dropdown = Select(driver.find_element_by_id('u_wJI_60871'))
checkin = driver.find_element_by_id('u_wJI_60861')
nights = driver.find_element_by_id('u_wJI_60870')
continue_btn = driver.find_element_by_class_name('button-primary')

first_name.send_keys('Luis')
last_name.send_keys('Rivas')
email.send_keys('*****@*****.**')
address.send_keys('DEMO')
country_dropdown.select_by_value('MX')
country_dropdown.select_by_visible_text('Mexico')
checkin.send_keys('11/18/2020')
nights.send_keys('5')
continue_btn.click()

driver.quit()
Пример #47
0
 def select_group_in_list(self, group):
     wd = self.app.wd
     select = Select(wd.find_element_by_xpath("//select[@name='to_group']"))
     select.select_by_value(group.id)
Пример #48
0
    def fill_case_information(self):
        select = Select(
            self.driver.find_element_by_id(self.case_type_dropbox_id))
        select.select_by_value('Ceza')

        select = Select(
            self.driver.find_element_by_id(self.case_type_detail_dropbox_id))
        select.select_by_value(('Asliye Ceza'))

        self.driver.find_element_by_id(self.case_subject_txtbox_id).send_keys(
            self.CASE_SUBJECT)

        select = Select(
            self.driver.find_element_by_id(self.case_city_dropbox_id))
        select.select_by_index(2)

        self.driver.find_element_by_id(
            self.case_city_region_txtbox_id).send_keys(self.CITY_REGION)

        # TODO Date picker test will be implemented by using DatePicker element rather than send_keys
        datefield = self.driver.find_element_by_id(
            self.case_create_date_time_picker_id)
        ActionChains(self.driver).move_to_element(datefield).click().send_keys(
            self.CASE_CREATE_DATE).perform()

        select = Select(
            self.driver.find_element_by_id(self.court_no_dropbox_id))
        select.select_by_value('0')

        self.driver.find_element_by_id(self.court_name_txtbox_id).send_keys(
            self.COURT_NAME)

        select = Select(
            self.driver.find_element_by_id(self.case_status_dropbox_id))
        select.select_by_value('Derdest')

        self.driver.find_element_by_id(self.sheet_no_txtbox_id).send_keys(
            self.SHEET_NO)

        self.driver.find_element_by_id(self.case_value_txtbox_id).send_keys(
            self.CASE_VALUE)

        select = Select(
            self.driver.find_element_by_id(
                self.case_value_currency_dropbox_id))
        select.select_by_value('USD')

        self.driver.find_element_by_id(
            self.case_extra_year_txtbox_id).send_keys(self.EXTRA_YEAR)

        self.driver.find_element_by_id(self.case_extra_no_txtbox_id).send_keys(
            self.EXTRA_NO)

        self.driver.find_element_by_id(
            self.case_decision_year_txtbox_id).send_keys(self.DECISION_YEAR)

        self.driver.find_element_by_id(
            self.case_decision_year_no_txtbox_id).send_keys(
                self.DECISION_YEAR_NO)

        self.driver.find_element_by_id(
            self.case_decision_date_txtbox_id).send_keys(self.DECISION_DATE)

        self.driver.find_element_by_id(
            self.case_decision_date_no_txtbox_id).send_keys(
                self.DECISION_DATE_NO)

        self.driver.find_element_by_id(
            self.case_final_date_txtbox_id).send_keys(self.CASE_FINAL_DATE)

        self.driver.find_element_by_id(self.case_add_btn_id).click()
Пример #49
0
checkme = driver.find_element_by_id('checkme')
print('checked:', checkme.is_selected())
# checkme.click()
driver.find_element_by_id('lblcheck').click()
print('checked:', checkme.is_selected())
time.sleep(2)

selected = driver.find_element_by_id('area')
area = Select(selected)
area.select_by_index(2)

time.sleep(2)
area.select_by_visible_text('上海')

time.sleep(2)
area.select_by_value('bj')

time.sleep(2)
ele_cell = driver.find_element_by_xpath(
    "//table[@id='myTable']/tbody/tr[2]/td[2]")
driver.find_element_by_id('username').send_keys(ele_cell.text)
print(ele_cell.text)
time.sleep(2)


def getCell(driver, tableId, row, col):
    xpath = "//table[@id='{}']/tbody/tr[{}]/td[{}]".format(tableId, row, col)
    ele_cell = driver.find_element_by_xpath(xpath)
    return ele_cell.text

Пример #50
0
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
driver.get("https://www.tdcc.com.tw/QStatWAR/inputframe.htm")
time.sleep(2)

#soup = BeautifulSoup(driver.page_source,'lxml')
#print(soup.prettify())

parentHandle = driver.window_handles[0]
parentHandle_title = driver.title
#print(parentHandle_title)

#<select name="Report" onchange="displayField(this)">
select = Select(driver.find_element_by_name('Report'))
#<option value="indw003">上櫃混藏保管有價證券週餘額表</option>
select.select_by_value('indw003')

#<input type="submit" value="查詢" name="queryButton">
confirm_button = driver.find_element_by_name('queryButton')

confirm_button.click()
time.sleep(5)
childHandle = driver.window_handles[1]
driver.switch_to.window(childHandle)

#code to extract data to excel
soup = BeautifulSoup(driver.page_source, 'lxml')
#weeklyVol = soup.find("table", attrs={"class":"mt"})
#print(soup.prettify)
time.sleep(3)
Пример #51
0
 def linkman_list_relationship(self, number):
     value = 'linkmanList' + number + '_relationship'
     linkman_relationship = Select(self.find_element_by_id(value))  # 实例化Select
     linkman_relationship.select_by_value('2')
Пример #52
0
def searchSeats(username,password,courseCode,registered):

    driver = webdriver.Chrome()
    driver.get("http://one.uf.edu/login/")

    try:
        ele = driver.find_element_by_xpath("/html[@class='ng-scope']/body[@class='uf-body layout-row']/div[@class='layout-column flex']/md-content[@id='main']/root[@id='root']/div[@class='root-view ng-scope']/uf-login[@class='ng-scope ng-isolate-scope']/div[@id='ufLogin']/md-card[@class='md-whiteframe-2dp layout-padding _md']/md-list[@class='layout-align-center-center layout-column']/md-list-item[@class='login-item md-no-proxy _md md-clickable'][1]/button[@class='md-primary md-raised md-ink-ripple login-button md-button']")
        ele.click()
        driver.implicitly_wait(5)

        ele = driver.find_element_by_id("username")
        # ele.clear()
        ele.send_keys(username)
        ele = driver.find_element_by_id("password")
        # ele.clear()
        ele.send_keys(password)
        ele = driver.find_element_by_id("submit")
        ele.click()
    except Exception as ex:
        print "Failure at Login"
        print(ex)
        driver.close()
        return {"id":5,"seats":"", "registered": False}
    try:
        # ele = driver.find_element_by_xpath("/html[@class='ng-scope']/body[@class='uf-body layout-row']/div[@class='layout-column flex']/md-content[@id='main']/root[@id='root']/div[@class='ng-scope']/uf-tab[@class='ng-scope ng-isolate-scope']/md-tabs[@id='ufTab']/md-tabs-content-wrapper[@class='_md']/md-tab-content[@id='tab-content-4']/div[@class='ng-scope ng-isolate-scope']/div[@class='ng-scope']/uf-panel[@class='ng-isolate-scope']/div[@id='ufPanel']/md-grid-list[@class='ng-scope ng-isolate-scope _md']/md-grid-tile[@class='ng-scope ng-isolate-scope'][2]/figure/uf-card[@class='uf-card card-wrapper ng-scope ng-isolate-scope']/div[@class='card-wrapper']/div[@class='card-wrapper ng-scope']/myschedule-card[@class='ng-scope ng-isolate-scope']/div[@id='myscheduleCard']/md-card[@class='_md']/md-card-actions[@class='layout-align-start-center layout-row']/a[@class='md-raised md-primary md-button md-ink-ripple']")
        #
        # ele.click()
        driver.get("https://one.uf.edu/myschedule/")

        ele = driver.find_element_by_xpath("/html[@class='ng-scope']/body[@class='uf-body ng-scope layout-row']/div[@class='layout-column flex']/md-content[@id='main']/div[@class='ng-scope flex-noshrink']/div[@id='termContainer']/md-card[@class='uf-card ng-scope _md flex-xs-100 flex-sm-45 flex-gt-sm-30']/md-card-action[@class='layout-align-start-start layout-column']/a[@class='md-raised md-primary md-button ng-scope md-ink-ripple']")

        ele.click()

        ele = driver.find_element_by_xpath("/html[@class='ng-scope']/body[@class='uf-body ng-scope layout-row']/div[@class='layout-column flex']/md-content[@id='main']/div[@class='ng-scope flex-noshrink']/section[@class='schedule-box-md-container ng-scope flex']/div[@id='scheduleBox']/div[@class='schedule-block']/div[@class='schedule-title hide-in-print-view ng-scope']/a[@class='add-course ng-scope']")

        ele.click()

        # ele = driver.find_element_by_xpath("/html[@class='ng-scope']/body[@class='uf-body ng-scope layout-row registration']/div[@class='layout-column flex']/md-content[@id='main']/div[@class='ng-scope flex-noshrink']/section[@class='search-layout ng-scope flex-none']/md-content[@class='center-content _md layout-row flex reg-content']/div[@id='ufSOC']/uf-semesters/div[@id='subHeader']/button[@class='md-button md-ink-ripple']")
        # ele.click()

        ele = Select(driver.find_element_by_id("progLevel"))
        ele.select_by_value("UGRD")

        ele = driver.find_element_by_id("courseCode")
        ele.send_keys(courseCode)

        ele = driver.find_element_by_class_name("filter-sidebar-search-button")
        ele.click()

        backdrop = driver.find_element_by_class_name("md-sidenav-backdrop")
        WebDriverWait(driver,1000).until(
            EC.invisibility_of_element_located((By.CLASS_NAME, "md-sidenav-backdrop"))
        )

        ele = driver.find_element_by_class_name("course-code")
        ele.click()

        ele = driver.find_element_by_class_name("section-open-seats")

        seats = ele.text
    except Exception as ex:
        print "Script failure after login"
        print(ex)
        traceback.print_exc()
        #driver.close()
        return {"id":4,"seats":"", "registered":False}

    if seats == "Open Seats: 0":

        driver.close();
        return {"id":2,"seats":seats, "registered":False}

    else:

        try:
            ele = driver.find_element_by_class_name("section-add-section ng-scope")
            ele.click()

            ele = driver.find_element_by_class_name("btn btn-primary modal-confirm-btn")
            ele.click()

            ele = driver.find_element_by_class_name("btn btn-primary modal-confirm-btn ng-scope")
            ele.click()
        except Exception as ex:
            driver.close()
            print(ex)
            print "Open seat but script failure before registration"
            return {"id":3,"seats":seats, "registered":False}
        driver.close()
        print seats
        return {"id":1,"seats":seats, "registered":True}
Пример #53
0
    if i<10:
        regno = '2015UGCS00' + roll
    else: 
        regno = '2015UGCS0' + roll
    
    driver.find_element_by_name('txtRegno').clear()
    driver.find_element_by_name('txtRegno').send_keys(regno)
    driver.find_element_by_name('btnimgShow').click()

    if is_alert_present() == True:
    	driver.close()
    	driver = webdriver.Firefox()
    	driver.get('http://14.139.205.172/web_new/Default.aspx')
    else:
        sem = Select(driver.find_element_by_name('ddlSemester'))
        sem.select_by_value('6')
        showresult = driver.find_element_by_name('btnimgShowResult')
        showresult.click()
        res = driver.page_source
        soup = bs4.BeautifulSoup(res,'lxml')
        name = soup.select('#lblSName')
        name = str(name[0].text)
        cg = soup.select('#lblCPI')
        cg = float(cg[0].text)
        cg=str(cg)

        with open('result.csv', 'a') as f:
            f.write(regno+","+name+","+cg+"\n")

df=pd.read_csv('result.csv')
df=df.sort_values('CGPA',ascending=[False])
Пример #54
0
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time


link = "http://suninjuly.github.io/selects1.html"

try:
    browser = webdriver.Chrome()
    browser.get(url=link)

    num1 = int(browser.find_element_by_id(id_="num1").text)
    num2 = int(browser.find_element_by_id(id_="num2").text)
    sum_of_numbers = str(num1 + num2)

    select_obj = Select(browser.find_element_by_id(id_="dropdown"))
    select_obj.select_by_value(value=sum_of_numbers)

    submit_button = browser.find_element_by_class_name(name="btn")
    submit_button.click()
finally:
    time.sleep(20)
    browser.quit()
Пример #55
0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time

link = 'http://suninjuly.github.io/selects2.html'

try:
    driver = webdriver.Chrome('../drivers/chromedriver.exe')
    driver.get(link)

    num1 = driver.find_element(By.ID, 'num1')
    num1_value = int(num1.text)

    num2 = driver.find_element(By.ID, 'num2')
    num2_value = int(num2.text)

    result = num1_value + num2_value

    select = Select(driver.find_element(By.ID, 'dropdown'))
    select.select_by_value(str(result))

    submit_btn = driver.find_element(By.CSS_SELECTOR,
                                     'button[type = "submit"]')
    submit_btn.click()
finally:
    time.sleep(10)
    driver.quit()
Пример #56
0
def set_basic_info_booking(destination, adult_num, child_num, cktin_date,
                           cktout_date):
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import Select
    import re
    import time

    url = 'https://www.booking.com/'

    chrome_options = Options()
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome()
    try:
        driver.get(url)
    except:
        print("Connection Failure")
    driver.maximize_window()
    driver.implicitly_wait(15)

    #Set destination
    dest = driver.find_element_by_xpath("//input[@type='search']")
    dest.send_keys(destination)

    #open calender
    cals = driver.find_elements_by_xpath(
        "//button[@aria-label='Open calendar']")
    cals[0].click()

    #format the checkin time
    cktin_date_format = time.strptime(cktin_date, "%Y-%m-%d")
    ckt_year = cktin_date_format.tm_year
    ckt_mon = cktin_date_format.tm_mon

    #find the calendar
    while True:
        cals = driver.find_elements_by_xpath(
            "//div[@class='bui-calendar__month']")
        cal = cals[0].text
        cal_date_format = time.strptime(cal, "%B %Y")
        cal_year = cal_date_format.tm_year
        cal_mon = cal_date_format.tm_mon
        if (cal_year != ckt_year) or (cal_mon != ckt_mon):
            driver.find_element_by_xpath(
                "//div[@data-bui-ref='calendar-next']").click()
        else:
            break

    start_dates = driver.find_elements_by_xpath(
        "//td[@class='bui-calendar__date'][@data-bui-ref='calendar-date']")

    #click checkin date
    for start_date in start_dates:
        if cktin_date.strip() == start_date.get_attribute('data-date').strip():
            start_date.click()

    #click checkout date
    for start_date in start_dates:
        if cktout_date.strip() == start_date.get_attribute(
                'data-date').strip():
            start_date.click()

    person_button = driver.find_element_by_xpath(
        "//label[@for='xp__guests__input']")
    person_button.click()

    #set people
    #person+button
    add_button = driver.find_elements_by_xpath(
        "//button[@type='button'][@class='bui-button bui-button--secondary bui-stepper__add-button']"
    )
    add_button = add_button[1:]

    #person-button
    sub_button = driver.find_elements_by_xpath(
        "//button[@type='button'][@class='bui-button bui-button--secondary bui-stepper__subtract-button']"
    )
    sub_button = sub_button[1:]

    while True:
        guests = driver.find_element_by_class_name("xp__guests__count").text
        adult_web = int(re.findall('\d+', guests)[0])
        child_web = int(re.findall('\d+', guests)[1])
        adult_num = int(adult_num)
        child_num = int(child_num)

        if (adult_web != adult_num) or (child_web != child_num):
            try:
                select_a = Select(driver.find_element_by_name('group_adults'))
                select_a.select_by_value(str(adult_num))
                select_c = Select(
                    driver.find_element_by_name('group_children'))
                select_c.select_by_value(str(child_num))
                break
            except:
                if adult_web > adult_num:
                    sub_button[0].click()
                elif adult_web < adult_num:
                    add_button[0].click()

                if child_web > child_num:
                    sub_button[1].click()
                elif child_web < child_num:
                    add_button[1].click()
        else:
            break

    #click submit
    submit = driver.find_element_by_xpath(
        "//button[@type='submit'][@data-sb-id='main']")
    submit.click()

    return driver
Пример #57
0
    #Находим элемент на странице, забираем значение атрибутов
    x_element = browser.find_element_by_id("num1")
    x = x_element.text

    y_element = browser.find_element_by_id("num2")
    y = y_element.text

    #Производим вычисления
    def calc(x, y):
        return str(int(x) + int(y))

    s = calc(x, y)

    #открываем выпадающий список и находим значение в нём

    select = Select(browser.find_element_by_tag_name("select"))
    select.select_by_value(s)

    #нажимаем на кнопку

    button = browser.find_element_by_class_name("btn")
    button.click()

finally:
    # успеваем скопировать код за 30 секунд
    time.sleep(10)
    # закрываем браузер после всех манипуляций
    browser.quit()

# не забываем оставить пустую строку в конце файла
Пример #58
0
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=chrome_options)
'''
url = "http://192.168.178.12:8060/redmine/login"
driver.get(url)
driver.maximize_window()
wait = WebDriverWait(driver, timeout=10)
driver.find_element_by_id("username").send_keys("wenqiang")
driver.find_element_by_id("password").send_keys("123456")
driver.find_element_by_name("login").click()
driver.find_element_by_link_text(u"指派给我的问题").click()
driver.find_element_by_id("add_filter_select").click()
s1 = Select(driver.find_element_by_id("add_filter_select"))  # 实例化Select
s1.select_by_value("tracker_id")  #选择value="tracker_id"的项
s1.select_by_value("member_of_group")
s1.select_by_value("created_on")
driver.find_element_by_id("cb_assigned_to_id").click()  #取消勾选
s2 = Select(driver.find_element_by_id("operators_status_id"))  # 实例化Select
s2.select_by_value("*")  #选择value="跟踪"的项
s3 = Select(driver.find_element_by_id("values_tracker_id_1"))  # 实例化Select
s3.select_by_value("13")  #选择value="跟踪"的项
s4 = Select(driver.find_element_by_id("values_member_of_group_1"))  # 实例化Select
s4.select_by_value("321")  #选择value="跟踪"的项
s5 = Select(driver.find_element_by_id("operators_created_on"))  # 实例化Select
s5.select_by_value("m")  #选择value="跟踪"的项
driver.find_element_by_link_text(u"应用").click()
driver.find_element_by_class_name("csv").click()
driver.find_element_by_id("csv_columns_all").click()  #勾选
driver.find_element_by_css_selector(
Пример #59
0
class Crwal_Table:
    def __init__(self):
        self.options = webdriver.ChromeOptions()
        # self.options.add_argument('headless')
        self.options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/61.0.3163.100 Safari/537.36")

        self.browser = None
        self.year = None
        self.semester = None
        self.dept_list = []
        self.semester_trans = {'1' : '1', '2' : '3', '여름' : '2', '겨울' : '4'}
        self.dept_eles = None

    def get_year_obj(self, rq_year):
        year = self.browser.find_element_by_name('ag_ledg_year')
        self.year = Select(year)
        self.year.select_by_value('20' + rq_year)


    def get_semester_obj(self, rq_semester):
        semester = self.browser.find_element_by_name('ag_ledg_sessn')
        self.semester = Select(semester)
        self.semester.select_by_value(self.semester_trans[rq_semester])


    def lecture_home(self, year, semester):
        if self.browser.current_url != "https://wis.hufs.ac.kr/src08/jsp/lecture/LECTURE2020L.jsp":
            self.browser.get("https://wis.hufs.ac.kr/src08/jsp/lecture/LECTURE2020L.jsp")

        if not self.year:
            self.get_year_obj(year)
            time.sleep(0.3)
            self.get_semester_obj(semester)

        dept_eles = self.browser.find_element_by_name('ag_crs_strct_cd')
        if len(self.dept_list) == 0:
            for i in dept_eles.find_elements_by_tag_name('option'):
                self.dept_list.append(i.text.strip()[6:].split('(')[0].strip())

        self.dept_eles = Select(dept_eles)
        return self.dept_eles

    def make_timetable(self, major, rq_year, rq_semester):

        if major == None:
            return None

        try:
            with open(rq_year + '-' + rq_semester + ' ' + major + '.txt', 'r', encoding="UTF-8") as file:
                class_list = file.readlines()
                depart = Department(major)
                print(depart.name, '데이터 수집 중')
                for i in class_list:
                    i = i.split(" # ")
                    area, year, subject, syllabus, required, online, foreign, team_teaching, prof, credit, class_time, restrict_num, note, stars = i
                    depart.insert_class(Class(area, year, subject, syllabus, required, online, foreign,
                                              team_teaching, prof, credit, class_time, restrict_num, note, stars))
            print("데이터 수집 완료")
            return depart

        except:
            if not self.browser:
                self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=self.options)
            dept_eles = self.lecture_home(rq_year, rq_semester)

            major_index = None
            for i in range(len(self.dept_list)):
                if major.lower() in self.dept_list[i].lower():
                    major_index = i
                    break
            print(self.dept_list[major_index], '데이터 수집 중')

            if major_index == None:
                raise Exception("학과를 정확히 입력해주세요!")

            # major_index = self.dept_list.index(major)
            depart = Department(self.dept_list[major_index])
            dept_eles.select_by_index(major_index)

            time.sleep(0.5)
            html = bs(self.browser.page_source, 'html.parser')

            tbody = html.findAll('tbody')
            trs = tbody[-1].findAll('tr')[1:]

            for i in trs:
                tds = i.findAll('td')
                area = tds[1].get_text().strip()
                year = tds[2].get_text().strip()
                subject = tds[4].get_text().strip().splitlines()
                subject = " / ".join(subject)
                try:
                    syllabus = tds[5].find('a')['href'].split('\'')
                    ag_1 = syllabus[1]
                    ag_2 = syllabus[3]
                    ag_3 = syllabus[5]
                    ag_4 = syllabus[7]
                    syllabus = "https://wis.hufs.ac.kr/src08/jsp/lecture/syllabus.jsp?mode=print&ledg_year=" \
                               +str(ag_1)+"&ledg_sessn="+str(ag_2)+"&org_sect="+str(ag_3)+"&lssn_cd="+str(ag_4)
                except:
                    syllabus = 'None'

                required = tds[6]
                if required.find('img'):
                    required = 'O'
                else:
                    required = required.get_text()

                online = tds[7]
                if online.find('img'):
                    online = 'O'
                else:
                    online = online.get_text()

                foreign = tds[9]
                if foreign.find('img'):
                    foreign = 'O'
                else:
                    foreign = foreign.get_text()

                team_teaching = tds[10]
                if team_teaching.find('img'):
                    team_teaching = 'O'
                else:
                    team_teaching = team_teaching.get_text()

                prof = tds[11].get_text().strip().split('(')[0].strip()
                credit = tds[12].get_text().strip()
                class_time = tds[14].get_text().strip()
                restrict_num = tds[15].get_text().strip()
                note = tds[16].get_text().strip()

                if len(note) == 0:
                    depart.insert_class(Class(area, year, subject, syllabus, required, online, foreign,
                                              team_teaching, prof, credit, class_time, restrict_num))
                else:
                    depart.insert_class(Class(area, year, subject, syllabus, required, online, foreign,
                                              team_teaching, prof, credit, class_time, restrict_num, note))

            self.all_courses(depart, rq_year, rq_semester)
        print("데이터 수집 완료")
        return depart


    def get_avg_stars(self, dept_obj1, dept_obj2, grade):
        if not self.browser:
            self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=self.options)
        browser = self.browser
        browser.get("https://everytime.kr/lecture")
        try:
            print('로그인 시도')
            id = browser.find_element_by_name("userid")
            id_input = input('아이디 입력 : ')
            id.send_keys(id_input)

            pw = browser.find_element_by_name("password")
            pw_input = input('비밀번호 입력 : ')
            pw.send_keys(pw_input)

            login = browser.find_element_by_class_name('submit')
            login.click()
            print('에브리타임 로그인 성공')
        except:
            print('로그인 실패')
            return

        fst_class_list = dept_obj1.classes
        scd_class_list = None
        if dept_obj2 != None:
            scd_class_list = dept_obj2.classes

        def course_insert(class_list):
            for course in class_list:

                if course.year not in grade or len(course.prof) == 0:
                    continue
                else:
                    if (fst_class_list == class_list and '이중' in course.area) \
                            or (scd_class_list == class_list and '1전공자 전용' in course.note):
                        continue

                while True:
                    try:
                        input_box = browser.find_element_by_name('keyword')
                        submit_btn = browser.find_element_by_class_name('submit')
                        input_box.send_keys(' ')
                        input_box.send_keys(course.subject.split(' / ')[0])
                        browser.execute_script("arguments[0].click();", submit_btn)
                        time.sleep(0.5)
                        if course.prof in browser.page_source:
                            profs= browser.find_element_by_xpath("//*[contains(text(), '" + course.prof + "')]")
                        else:
                            course.stars = '-'
                            browser.back()
                            break
                        browser.execute_script("arguments[0].click();", profs)
                        time.sleep(0.5)
                        stars = browser.find_element_by_class_name('value').text
                        if stars == '0':
                            stars = '-'
                        course.stars = stars
                        browser.back()
                        browser.back()
                        break

                    except:
                        pass
                    try:
                        popup = browser.find_element_by_class_name('close')
                        browser.execute_script("arguments[0].click();", popup)
                    except:
                        continue
        print('강의평 가져오는중...')
        course_insert(fst_class_list)
        print('1전공 완료')
        if scd_class_list:
            course_insert(scd_class_list)
            print('2전공 완료')
        # browser.close()


    def all_courses(self, dept_obj, year, semester):
        with open(year + '-' + semester + ' ' + dept_obj.name + '.txt', 'w', encoding="UTF-8") as file:
            for course in dept_obj.classes:
                file.write(" # ".join(course()) + "\n")
Пример #60
0
        pokemon = "muk (alolan)"
    if pokemon == "mewtwo":
        pokemon = "mewtwo (Armored)"
    pokemons[pokemon] = [level, attack, defence, stamina]

pokemon_combinations = list(combinations(pokemons, 3))
print(pokemons)
#op.add_argument('--headless')
driver = webdriver.PhantomJS()
driver.implicitly_wait(10)
for team in pokemon_combinations:
    driver.get("https://pvpoke.com/team-builder/")
    time.sleep(3)
    el = driver.find_element_by_xpath("/html/body/div/div/div[1]/select[1]")
    select = Select(el)
    select.select_by_value("2500")
    time.sleep(0.5)
    print(team)
    f2.write(str(team) + "\n")
    for pokemon in team:
        driver.find_element_by_xpath(
            "/html/body/div/div/div[2]/div[1]/div/div[1]/button[1]").send_keys(
                Keys.ENTER)
        time.sleep(0.5)
        try:
            driver.find_element_by_xpath(
                "/html/body/div[2]/div/div[3]/div[1]/input").send_keys(pokemon)
        except:
            print("error cant find")
            f2.write("error\n")