Exemplo n.º 1
0
 def create_blog_post(self, publish):
     posts_button = self.driver.find_element_by_id("wp-admin-bar-new-content")
     posts_button.click()
     assert 'Add New Post' in self.driver.title, 'failed to reach the New Post page.'
     
     title_input = self.driver.find_element_by_name("post_title") 
     title_input.send_keys(self.bp['title'])
     
     self.insert_post_body()
     self.complete_seo_form()
     self.choose_category()
     
     tags_input = self.driver.find_element_by_id("new-tag-post_tag")
     tags_input.send_keys(self.bp['seo_keywords'])
     
     self.driver.execute_script("document.body.scrollTop = document.documentElement.scrollTop = 0;")
     if publish:
         publish_button = self.driver.find_element_by_id("publish")
         publish_button.click()
         
         expectation = EC.text_to_be_present_in_element((By.ID,'message'), "Post published.")
         self.wait_until(expectation, "post failed to publish.")
     else:
         save_button = self.driver.find_element_by_id("save-post")
         save_button.click()
         
         expectation = EC.text_to_be_present_in_element((By.ID,'message'), "Post draft updated.")
         self.wait_until(expectation, "post failed to save.")
     
     anchor = self.driver.find_element_by_css_selector("#message p a")
     return anchor.get_attribute('href')
Exemplo n.º 2
0
    def wait_to_contain(self, item=None, text=None):
        """Wait for item like a label to contain text.

           * If there are no spaces in item, waits for element with HTML id "item" to contain 'text'
           * "first class1" - waits for first item with  HTML class "class1" to contain text.
           * "2nd class1 class2" - waits for the 2nd item with HTML classes class1 and class2 to contain 'text'.
           * "last class1 class2" - waits for the last element with classes class1 and class2 to contain 'text'.
        """
        item = HitchSeleniumItem(item)
        if item.is_id:
            WebDriverWait(self.driver, self.wait_for_timeout).until(
                EC.text_to_be_present_in_element((By.ID, item.html_id), text)
            )
        else:
            full_xpath = """//*[{}][{}]""".format(
                " and ".join([
                    """contains(concat(' ', normalize-space(@class), ' '), ' {} ')""".format(
                        class_name
                    ) for class_name in item.html_classes]
                ),
                str(item.index + 1) if item.index >= 0 else "last()"
            )

            WebDriverWait(self.driver, self.wait_for_timeout).until(
                EC.text_to_be_present_in_element(
                    (By.XPATH, full_xpath), text
                )
            )
Exemplo n.º 3
0
def main():
    flags = docopt.docopt(__doc__)
    sut_url = flags['--url'] or 'http://127.0.0.1:4000/mailsignature/'
    persons_name = flags['<persons-name>']
    banner = flags['<banner>']
    
    options = webdriver.ChromeOptions()
    options.add_argument('headless')

    #browser = webdriver.Firefox()
    browser = webdriver.Chrome(chrome_options=options)
    browser.get(sut_url)

    WebDriverWait(browser, 10).until(
        EC.text_to_be_present_in_element((By.ID, "user-options"), persons_name)
    )
    users = Select(browser.find_element_by_id("user-options"))
    users.select_by_visible_text(persons_name)

    banners = Select(browser.find_element_by_id("banner-options"))
    banners.select_by_value(banner)

    browser.find_element_by_id("user-options").submit() 

    WebDriverWait(browser, 10).until(
        EC.text_to_be_present_in_element((By.ID, "name"), persons_name)
    )

    body = browser.find_element_by_xpath("/html/body")
    print(body.get_attribute("innerHTML"))

    browser.quit()
Exemplo n.º 4
0
    def test_delete_layer(self):
        """ Delete the layer """

        self.get(self.url)

        # Wait for the tables to load to avoid a race condition where the
        # toaster tables have made an async request. If the layer is deleted
        # before the request finishes it will cause an exception and fail this
        # test.
        wait = WebDriverWait(self.driver, 30)

        wait.until(EC.text_to_be_present_in_element(
            (By.CLASS_NAME,
             "table-count-recipestable"), "0"))

        wait.until(EC.text_to_be_present_in_element(
            (By.CLASS_NAME,
             "table-count-machinestable"), "0"))

        self.click('a[data-target="#delete-layer-modal"]')
        self.wait_until_visible("#delete-layer-modal")
        self.click("#layer-delete-confirmed")

        notification = self.wait_until_visible("#change-notification-msg")
        expected_text = "You have deleted 1 layer from your project: %s" % \
            self.imported_layer_version.layer.name

        self.assertTrue(expected_text in notification.text,
                        "Expected notification text \"%s\" not found instead"
                        "it was \"%s\"" %
                        (expected_text, notification.text))
def PageNav_Main (EntryNum):
	#Page up / down until it is posible to access page containing entry with nav panel
	PageSource=str(driver.page_source)
	Min_NavButtons,Max_NavButtons=PageNav_GetNavOptions(PageSource)
	iteration=0
	while iteration<=10000 and not (EntryNum>=Min_NavButtons and EntryNum<=Max_NavButtons):
		if EntryNum>Max_NavButtons:
			Containstxt=str(Max_NavButtons-8)+' - '+str(Max_NavButtons+1)
			driver.find_element_by_xpath('//*[@id="_bld_result_frm:_result_tbl_paginator_bottom"]/span[4]/span[10]').click()
			WebDriverWait(driver, 30).until(EC.text_to_be_present_in_element((By.ID, '_bld_result_frm:_result_tbl_paginator_bottom'), Containstxt))
			iteration+=1
		elif EntryNum<Min_NavButtons:
			Containstxt=str(Min_NavButtons+1)+' - '+str(Min_NavButtons+10)
			driver.find_element_by_xpath('//*[@id="_bld_result_frm:_result_tbl_paginator_bottom"]/span[4]/span[1]').click()
			WebDriverWait(driver, 30).until(EC.text_to_be_present_in_element((By.ID, '_bld_result_frm:_result_tbl_paginator_bottom'), Containstxt))
			iteration+=1
		else:
			print('Error')
		PageSource=str(driver.page_source)
		Min_NavButtons,Max_NavButtons=PageNav_GetNavOptions(PageSource)
	
	# Determine which button should be pressed to access correct page and click that button
	Min_TableEntries,Max_TableEntries=PageNav_FindEntries(PageSource)

	if Min_TableEntries<=EntryNum and Max_TableEntries>=EntryNum:
		pass
	else:
		target_page=math.trunc(EntryNum/10)+1
		nav_target=target_page-(Min_NavButtons/10)
		Containstxt=str((target_page*10)-9)+' - '+str(target_page*10)
		target_page_xpath='//*[@id="_bld_result_frm:_result_tbl_paginator_bottom"]/span[4]/span['+str(nav_target)+']'
		driver.find_element_by_xpath(target_page_xpath).click()
		WebDriverWait(driver, 30).until(EC.text_to_be_present_in_element((By.ID, '_bld_result_frm:_result_tbl_paginator_bottom'), Containstxt))
Exemplo n.º 6
0
 def testExpectedConditionTextToBePresentInElement(self, driver, pages):
     pages.load('booleanAttributes.html')
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
     driver.execute_script("setTimeout(function(){var el = document.getElementById('unwrappable'); el.textContent = el.innerText = 'Unwrappable Expected text'}, 200)")
     WebDriverWait(driver, 1).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
     assert 'Unwrappable Expected text' == driver.find_element_by_id('unwrappable').text
 def get_response_body(self):
     # Wait for the response header to appear
     wait = WebDriverWait(self.driver, 10)
     self.response_body_field = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "pre.response.prettyprint")))  
     EC.text_to_be_present_in_element(self.response_body_field, "message")
     sleep(2)  # still need to add this to wait for text to show up in the response body; otherwise, we return to quickly
     return self.response_body_field.text 
Exemplo n.º 8
0
def login(mainCfg,driver):

    # go to expressov3 home
    driver.get(mainCfg['url'])
    
    # checking language
    # waiting for page reload with correct language
    while True:

        if driver.title == 'Expresso 3.0 - Por favor, insira seus dados de login':
            break

        # choosing language if not portuguese
        path = "//div/img"
        WebDriverWait(driver, mainCfg['timeout']).until(EC.visibility_of_element_located((By.XPATH,path)))
        localeButton = driver.find_element_by_xpath(path)
        localeButton.click()

        path = ".x-combo-list-item"
        WebDriverWait(driver, mainCfg['timeout']).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,path)))
        languagesList = driver.find_elements_by_css_selector(path)
        for i in languagesList:
            if i.text == mainCfg['language']:
                i.click()
                break

        # wait for loading portuguese language
        path = "//div[2]/span"
        WebDriverWait(driver, mainCfg['timeout']).until_not(EC.visibility_of_element_located((By.XPATH,path)))

        # waiting for loading portuguese window title
        WebDriverWait(driver, mainCfg['timeout']).until(EC.title_contains('Por favor, insira seus dados de login'))

    # find the element that's username 
    path = "//div[3]/div/input"
    WebDriverWait(driver, mainCfg['timeout']).until(EC.visibility_of_element_located((By.XPATH,path)))
    inputUsername = driver.find_element_by_xpath(path)
    inputUsername.send_keys(mainCfg['username'])
    
    # find the element that's password
    path = "//div[4]/div/input"
    WebDriverWait(driver, mainCfg['timeout']).until(EC.visibility_of_element_located((By.XPATH,path)))
    inputUserpasswd = driver.find_element_by_xpath(path)
    inputUserpasswd.send_keys(mainCfg['passwd'])
    
    # find the element that's login button
    path = "//button"
    WebDriverWait(driver, mainCfg['timeout']).until(EC.visibility_of_element_located((By.XPATH,path)))
    inputLoginbutton = driver.find_element_by_xpath(path)
    inputLoginbutton.click()

    if mainCfg['lastName'] is not None:
        # we have to wait for the page to refresh, the last thing that seems to be updated is the user's lastName
        path = "//td[2]/table/tbody/tr/td[2]/em/button"
        WebDriverWait(driver, mainCfg['timeout']).until(EC.text_to_be_present_in_element((By.XPATH,path),mainCfg['lastName']))
    else:
        # check for error in login
        path = '//div[2]/span'
        WebDriverWait(driver, mainCfg['timeout']).until(EC.text_to_be_present_in_element((By.XPATH,path),u'Usuário e/ou senha incorretos!'))
def Selenium_click(Click_ID,Wait_ID,Wait_Str):
	WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, Click_ID)))
	driver.find_element_by_id(Click_ID).click()
	#WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.ID, Wait_ID), Wait_Str))

	try:
		WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.ID, Wait_ID), Wait_Str))
	except:
		WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.ID, Wait_ID), Wait_Str))
Exemplo n.º 10
0
 def testExpectedConditionTextToBePresentInElement(self, driver, pages):
     if driver.capabilities['browserName'] == 'firefox' and driver.w3c:
         pytest.xfail("Marionette issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1297551")
     pages.load('booleanAttributes.html')
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
     driver.execute_script("setTimeout(function(){var el = document.getElementById('unwrappable'); el.textContent = el.innerText = 'Unwrappable Expected text'}, 200)")
     WebDriverWait(driver, 1).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
     assert 'Unwrappable Expected text' == driver.find_element_by_id('unwrappable').text
Exemplo n.º 11
0
 def delete(self):
     self.find_element(*self._link_locator).click()
     WebDriverWait(self.selenium, self.timeout).until(
         EC.visibility_of_element_located(self._delete_add_on_button_locator))
     self.selenium.find_element(*self._delete_add_on_button_locator).click()
     WebDriverWait(self.selenium, self.timeout).until(
         EC.text_to_be_present_in_element(self._delete_add_on_button_locator, 'Are you sure'))
     self.selenium.find_element(*self._delete_add_on_button_locator).click()
     WebDriverWait(self.selenium, self.timeout).until(
         EC.text_to_be_present_in_element(self._delete_confirmation_locator, 'This add-on has been deleted'))
Exemplo n.º 12
0
def test_home_page_contains_countdown(selenium):
    go_to_home_page(selenium)
    spec = By.ID, 'ending'
    WebDriverWait(selenium, 5).until(Or(
        expected_conditions.text_to_be_present_in_element(spec, 'in'),
        expected_conditions.text_to_be_present_in_element(spec, 'ago'),
    ))
    countdown = selenium.find_element(*spec).text.lower()
    assert 'in' in countdown or 'ago' in countdown
    assert countdown.startswith('project ends')
 def testExpectedConditionTextToBePresentInElement(self):
     self._loadPage('booleanAttributes')
     try:
         WebDriverWait(self.driver, 0.7).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
         self.fail("Expected TimeoutException to have been thrown")
     except TimeoutException as e:
         pass
     self.driver.execute_script("setTimeout(function(){var el = document.getElementById('unwrappable'); el.textContent = el.innerText = 'Unwrappable Expected text'}, 200)")
     WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))
     self.assertEqual('Unwrappable Expected text', self.driver.find_element_by_id('unwrappable').text)
Exemplo n.º 14
0
 def update_count(update_xpath: str):
     table_count, header_count = get_counts()
     spin = self.wait.until(EC.element_to_be_clickable(
         (By.XPATH, update_xpath)
     ))
     spin.click()
     self.wait.until_not(EC.text_to_be_present_in_element(
         (By.ID, 'cart-page-prods-count'), table_count
     ))
     self.wait.until_not(EC.text_to_be_present_in_element(
         (By.CLASS_NAME, 'js-cart-size'), header_count
     ))
Exemplo n.º 15
0
 def _compare_cell_value(self, xpath, value):
     # Initialize an instance of WebDriverWait with timeout of 5 seconds
     wait = WebDriverWait(self.driver, 5)
     try:
         wait.until(EC.text_to_be_present_in_element(
             (By.XPATH, xpath + "//span"), str(value)),
             CheckForViewDataTest.TIMEOUT_STRING
         )
     except Exception:
         wait.until(EC.text_to_be_present_in_element(
             (By.XPATH, xpath), str(value)),
             CheckForViewDataTest.TIMEOUT_STRING
         )
Exemplo n.º 16
0
def checkin():
    output_filename = join(dirname(abspath(__file__)), "ret")
    if not DEBUG and has_checkin():
        return
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = USER_AGENT
    browser = webdriver.PhantomJS(service_args=['--load-images=no'], desired_capabilities=dcap)
    browser.set_window_size(1024, 768)
    browser.get("http://www.smzdm.com/")

    try:
        WebDriverWait(browser, WAITTIME_BEFORE_CLICK).until(
            EC.element_to_be_clickable((By.CLASS_NAME, login_button_tag)),
            "timeout waiting for login button to load")
        element = browser.find_element_by_class_name(login_button_tag)
        element.click()

        login(browser)

        WebDriverWait(browser, WAITTIME_BEFORE_CLICK).until(
            EC.text_to_be_present_in_element(
                (By.CLASS_NAME, checkin_button_tag), u"签到"),
            "timeout waiting for checkin button to load")
        checkin_button = browser.find_element_by_class_name(checkin_button_tag)

        WebDriverWait(browser, WAITTIME_BEFORE_CLICK).until(
            EC.element_to_be_clickable((By.CLASS_NAME, checkin_button_tag)),
            "timeout waiting for checkin button to be clickable")
        WebDriverWait(browser, WAITTIME_AFTER_CLICK).until(
            EC.text_to_be_present_in_element(
                (By.CLASS_NAME, checkin_button_tag), u"签到"),
            "timeout waiting for page to load")
        checkin_button = browser.find_element_by_class_name(checkin_button_tag)
        checkin_button.click()
        print("click checkin")
        loop_try(browser)
        text_info = browser.find_element_by_class_name(checkin_button_tag).text
        with open(output_filename, "a") as fh:
            fh.write(str(datetime.datetime.now()) + "\t" + text_info.encode(
                "utf8") + "\n")
        print text_info.encode("utf8")
        browser.save_screenshot(SCREENSHOT_PATH)
    except selenium.common.exceptions.WebDriverException, err:
        page_source_file = join(dirname(abspath(__file__)), "page_source")
        tb = traceback.format_exc()
        print err
        print tb
        browser.save_screenshot(SCREENSHOT_PATH)
        send_warning_mail(str(err) + "\n" + tb)
        with open(page_source_file, "w") as fout:
            fout.write(browser.page_source.encode("utf-8"))
Exemplo n.º 17
0
 def get_button(self, is_on=False):
     if is_on:
         self.wait_for_element(By.CSS_SELECTOR, self.CSS_TEST_ROW_BUTTON_ON)
         WebDriverWait(self.browser,1).until(ec.text_to_be_present_in_element(
             (By.CSS_SELECTOR, self.CSS_TEST_ROW_BUTTON_ON), self.TEXT_DISABLE))
         btn = self.browser.find_element_by_css_selector(self.CSS_TEST_ROW_BUTTON_ON)
         self.assertEqual(btn.text, self.TEXT_DISABLE)
     else:
         self.wait_for_element(By.CSS_SELECTOR, self.CSS_TEST_ROW_BUTTON)
         WebDriverWait(self.browser,1).until(ec.text_to_be_present_in_element(
             (By.CSS_SELECTOR, self.CSS_TEST_ROW_BUTTON), self.TEXT_ENABLE))
         btn = self.browser.find_element_by_css_selector(self.CSS_TEST_ROW_BUTTON)
         self.assertEqual(btn.text, self.TEXT_ENABLE)
     return btn
Exemplo n.º 18
0
    def test_submitting_scores(self):
        """Tests submitting high scores."""
        self.login_user("wealthyplayer", "player")

        # Switch to game
        game = Game.objects.all().first()
        self.selenium.get('%s/game/%d' % (self.live_server_url, game.pk))

        # No highscores should exist yet
        top10 = self.selenium.find_element_by_css_selector('#top10')
        self.assertNotIn("0", top10.text)
        self.assertNotIn("10", top10.text)

        game_iframe = self.selenium.find_element_by_name("game_iframe")
        self.assertTrue(game_iframe)
        self.selenium.switch_to.frame(game_iframe)

        # Submit two highscores
        score = self.selenium.find_element_by_css_selector('#score')
        self.assertEqual("0", score.text)
        self.selenium.find_element_by_css_selector('#submit_score').click()

        self.selenium.find_element_by_css_selector('#add_points').click()
        self.selenium.find_element_by_css_selector('#submit_score').click()

        # Both scores should exist in the highscore list...
        self.selenium.switch_to_default_content()
        wait = WebDriverWait(self.selenium, 3)
        try:
            wait.until(EC.text_to_be_present_in_element(
                (By.ID, 'top10'),
                'wealthyplayer 0 points'))
            wait.until(EC.text_to_be_present_in_element(
                (By.ID, 'top10'),
                'wealthyplayer 10 points'))
        except TimeoutException:
            self.fail("High score not visible")

        # ... and in the database
        highscores = HighScore.objects.all()
        self.assertEqual(2, len(highscores))
        highscore1 = highscores[0]
        self.assertEqual(game, highscore1.game)
        self.assertEqual(0, highscore1.score)
        self.assertEqual("wealthyplayer", highscore1.player.user.username)
        highscore2 = highscores[1]
        self.assertEqual(game, highscore2.game)
        self.assertEqual(10, highscore2.score)
        self.assertEqual("wealthyplayer", highscore2.player.user.username)
    def test_reviewer_specification(self):
        # This tests whether or not it's possible to specify a review in the
        # commit summary and have it appear in the UI and be publishable.
        # Some validation occurs in the UI so it is possible to break
        # publishing but have it appear to work in other tests.
        self.create_users([
            ('*****@*****.**', 'password1', 'Jeremy Smith [:jsmith]'),
            ('*****@*****.**', 'password2', 'Mary Jane [:mary]'),
        ])
        self.create_ldap(b'*****@*****.**', b'mjane', 2001, b'Mary Jane')
        mjb = self.user_bugzilla('*****@*****.**')
        mjb.create_bug('TestProduct', 'TestComponent', 'bug1')

        lr = self.create_basic_repo('*****@*****.**', 'mjane')
        lr.write('foo', 'first change\n')
        lr.run(['commit', '-m', 'Bug 1 - Test reviewer specification; r=jsmith'])
        lr.run(['push'])

        self.reviewboard_login('*****@*****.**', 'password2')

        self.load_rburl('r/1')

        WebDriverWait(self.browser, 3).until(
            EC.text_to_be_present_in_element(
                (By.CLASS_NAME, 'mozreview-child-reviewer-list'), 'jsmith'))

        reviewers = self.browser.find_elements_by_class_name('mozreview-child-reviewer-list')
        self.assertEqual(len(reviewers), 1)
        self.assertEqual(reviewers[0].text, 'jsmith')
Exemplo n.º 20
0
    def wait_for_console(self, text, xpath=None):
        if xpath is None:
            xpath = "//div[@class='terminal-output']/div[last()]/div[1]"

        WebDriverWait(self.browser, 10).until(
            EC.text_to_be_present_in_element((By.XPATH, xpath), text)
        )
Exemplo n.º 21
0
        def get_student_assignments(index):
            self.navigate_to('assignments', student_index=index)
            option = self.driver.find_element_by_css_selector('select option[value="' + DURATION + '"]')
            option.click()
            WebDriverWait(self.driver, 10).until(
                EC.text_to_be_present_in_element(
                    (By.CLASS_NAME, 'clIGPTaskTimeLine'),
                    DURATION_STRING # FIXME: Make work for multiple durations
                )
            )

            soup = BeautifulSoup(self.driver.page_source)
            grade_rows = soup.select('.clIGPTaskGenTbl tr')
            grade_rows = grade_rows[1:] # Remove header row

            def get_text_if_not_empty(el):
                text = el.get_text(strip=True)
                return text if text != '-' else None

            data = []
            for row in grade_rows:
                children = map(get_text_if_not_empty, row.find_all('td'))
                data.append({
                    'student_index': index,
                    'course': children[0],
                    'period': children[1],
                    'assignment': children[2],
                    'type': children[3],
                    'score': children[4],
                    'due': children[5],
                    'remark': children[6],
                    'teacher': children[7]
                })

            return data
Exemplo n.º 22
0
 def buy_product(self):
     self.browser.get(self.product_path)
     self.wait_page_loading()
     self.click((By.ID, 'btn-to-basket'))
     self.wait.until_not(EC.text_to_be_present_in_element(
         (By.CLASS_NAME, 'js-mobile-cart-price'), '0'
     ))
Exemplo n.º 23
0
 def _check_success(self, xpath, text):
     try:
         WebDriverWait(self.driver, 10).until(EC.text_to_be_present_in_element((By.XPATH, xpath), text))
     except Exception, e:
         print e
         logging.debug("post message not appear on page, maybe post not successfully.")
         return
Exemplo n.º 24
0
    def login_is(self):
        self.login()
        logger.info('exec login_is def')
        test = EC.text_to_be_present_in_element(
                (By.CLASS_NAME,"ut"),self.names.decode('utf-8'))
        n = 0
        while n < 3:
	     
            try:
                #print test(self.bro)
                if test(self.bro):
                    logger.info('1')
                    logger.info('login in the weibo')
                    ret = self.bro.get_cookies()
		    print ret,self.bro.current_url
                    for cookie in ret:
                        self.cookies[str(cookie['name'])] = str(cookie['value'])
		    print self.cookies
		    self.gsid=self.cookies['SUB']
		    print self.gsid
                    break
                else:
                    logger.info('2')
                    n +=1
                    self.login()
            except:
                n += 1
                time.sleep(1)
                logger.info('4')

        logger.info('3')
        logger.info('n is %s' % n)
        if n >3:
            logger.info('not to login in weibo and quit')
            self.bro.quit()
Exemplo n.º 25
0
def test_recalc_invalid(admin_client, live_server, webdriver):
    selenium = webdriver()
    create_correct_sample_data()
    create_sample_characteristic_values()
    calc_rule = CalculationRule.objects.get(rule_name='calc_rule')
    calc_rule.rule_code = CALC_RULE_CODE
    calc_rule.save()
    try:
        selenium.get(live_server + '/recalc_characteristic_values/')
        login_as_admin(selenium)
        section_header = selenium.find_element_by_id('invalid_header')
        assert selenium.find_element_by_id('progress_value_0').text == "0%"
        progress_bar = selenium.find_element_by_class_name('progress-bar')
        assert progress_bar.get_attribute('style') == 'width: 0%;'
        assert section_header.text == '16'
        recalc_button = selenium.find_element_by_id('recalc_values')
        recalc_button.click()
        section_header = WebDriverWait(selenium, 5).until(
            EC.text_to_be_present_in_element((By.ID, 'invalid_header'), '0/16'))
        assert section_header
        assert selenium.find_element_by_id('progress_value_0').text == '100%'
        progress_bar = selenium.find_element_by_class_name('progress-bar')
        assert progress_bar.get_attribute('style') == 'width: 100%;'
    finally:
        selenium.quit()
Exemplo n.º 26
0
    def wait_until(self, minutes, seconds):
        CounterPageExt.get_webdriver_instance(self)

        timeout = int(minutes) * 60 + int(seconds) + 10

        WebDriverWait(driver, timeout).until(
            EC.text_to_be_present_in_element((By.ID, "stats"), "0h " + str(minutes) + "min " + str(seconds) + "sec"))
Exemplo n.º 27
0
    def test_removed_origin_display(self):
        """Ensure origin is displayed and removed properly."""
        self.add_test_origin("pbtest.org", "block")

        self.load_url(pbtest.PB_CHROME_OPTIONS_PAGE_URL)
        origins = self.driver.find_element_by_id("blockedResourcesInner")

        # Remove displayed origin.
        try:
            remove_origin_element = origins.find_element_by_xpath(
                './/div[@data-origin="pbtest.org"]' +
                '//div[@class="removeOrigin"]')
        except NoSuchElementException:
            self.fail("Tracking origin is not displayed")
        remove_origin_element.click()
        self.driver.switch_to.alert.accept()

        # Check tracker count.
        try:
            WebDriverWait(self.driver, 5).until(
                EC.text_to_be_present_in_element((By.ID, "count"), "0"))
        except TimeoutException:
            self.fail("Origin count should be 0 after deleting origin")

        # Check that no origins are displayed.
        try:
            origins = self.driver.find_element_by_id("blockedResourcesInner")
        except NoSuchElementException:
            origins = None
        error_message = "Origin should not be displayed after removal"
        self.assertIsNone(origins, error_message)
 def test_search_box_videos_play_on_click(self):
     """
     Clicking a search result cues up the video in the viewing pane. Video subject
     appears below the video
     """
     # Jane selects one of them, and 
     # a video begins playing in the central pane. The video subject appears
     # below the playing video.
     self.student_log_in_complete()  
     search_bar = self.search_for_activities('activity')
     
     dropdown = WebDriverWait(self.browser, 30).until(
             EC.presence_of_element_located((By.XPATH,'//li[@class="ui-menu-item"]')))
             
     search_bar.send_keys(Keys.ARROW_DOWN)
     search_bar.send_keys(Keys.RETURN)
     
     #self.assertTrue(self.check_exists_by_class_name('spinner'))
     #spinner = self.browser.find_element_by_class_name('spinner')
     #
     #loaded_wait = WebDriverWait(self.browser, 3).until(
     #        EC.staleness_of(spinner))
     wait = WebDriverWait(self.browser, 3).until(
             EC.text_to_be_present_in_element((By.ID, 'subject'), 'test activity')
         )
             
     self.check_test_activity_video_playing()
Exemplo n.º 29
0
 def assert_element_text(self, how, what, text, message):
     try:
         return WebDriverWait(self.driver, 10).until(
             EC.text_to_be_present_in_element((how, what), text)
         )
     except:
         self.fail(message)
    def test_enforcement_detail_page_tab2(self):
        """
        Test that the enforcement detail page has the tab and accordion items we expect
        :return:
        """
        # I want to see the specific drugs involved in a states' enforcement reports

        item = CATEGORIES[2]
        self.driver.get('%s/search/enforcements/?q=%s' % (self.live_server_url, item['search'], ))
        self.assertIn(item['detail'], self.driver.find_element_by_tag_name('h1').text)
        self.assertIn(item['search'], self.driver.find_element_by_tag_name('h1').text)

        # we should have two tabs
        self.assertEqual(2, len(self.driver.find_element_by_class_name('ui-tabs-nav').find_elements_by_tag_name('li')))

        # I want to see drugs with this adverse event, so i click that tab
        self.driver.find_element_by_id('ui-id-2').click()

        # I see a chart with drug information and I click the first drug to go to its detail page
        chart_bar = self.driver.find_element_by_xpath(
            "//div[@id='enforcementChart']//*[local-name()='svg']//*[local-name()='g'][@class='highcharts-series highcharts-tracker']/*[local-name()='rect']")
        chart_bar.click()

        WebDriverWait(self.driver, 3).until(
            EC.text_to_be_present_in_element((By.TAG_NAME, 'h1'), 'Drug Details'))
        self.assertIn('Drug Details', self.driver.find_element_by_tag_name('h1').text)
def calc(x):
  return str(math.log(abs(12*math.sin(int(x)))))


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

    book = browser.find_element_by_id("book")
    browser.execute_script("return arguments[0].scrollIntoView(true);", book)

    # Price
    price = WebDriverWait(browser, 15).until(EC.text_to_be_present_in_element((By.ID, "price"), "$100"))

    # assert "$100" in price.text

    # Book

    book.click()
    # Отправляем заполненную форму
    # button = browser.find_element_by_css_selector("button.btn")
    # button.click()
    x_element = browser.find_element_by_id ("input_value")
    x = x_element.text
    y = calc(x)

    button = browser.find_element_by_id("solve")
    browser.execute_script("return arguments[0].scrollIntoView(true);", button)
Exemplo n.º 32
0
def explicit_wait_methods():
    # Variables and objects
    url = "https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver"
    # click button:  #populate-text
    # explictitly wait until
    # text_to_be_present_in_element(locator,text_) -- "Selenium"
    # locators: h2 (id), //h2[@id='h2'] (xpath), #h2 (css selector)
    # driver.find_element_by_xpath("//h2[@id='h2' and text()='Selenium Webdriver']") -- this is not good
    msg_xpath = "//h2[@id='h2']"
    msg_id = "h2"
    msg_css_selector = "#h2"
    # locator1 = (By.XPATH, msg_xpath)
    extd_txt = "Selenium Webdriver"
    wdwait = WebDriverWait(driver, 60)

    # Steps starts here
    driver.get(url)
    element = driver.find_element_by_id(
        "populate-text")  # finding the button to click

    print("## Case 1: text_to_be_present_in_element")
    element = driver.find_element_by_id(
        "populate-text")  # finding the button to click
    # printing the message of the h2 before clicking
    print(
        f"expected message text: {driver.find_element_by_xpath(msg_xpath).text}"
    )
    msg_txt = driver.find_element_by_xpath(msg_xpath)
    print(f"Current message text: {msg_txt.text}")
    element.click()

    print("waiting until expected text to appear ...")
    # WebDriverWait(driver, 60).until(expected_conditions.text_to_be_present_in_element((By.XPATH, msg_xpath), extd_txt))
    msg = wdwait.until(
        EC.text_to_be_present_in_element((By.XPATH, msg_xpath), extd_txt))
    print(f"did message appear now? - {msg}")
    print(
        f"expected message text: {driver.find_element_by_xpath(msg_xpath).text}"
    )

    print(f"New (expected) message text: {msg_txt.text}")

    print("## Case 2: visibility_of_element_located")
    display_btn_id = "display-other-button"
    driver.find_element_by_id(display_btn_id).click()
    print("waiting until enabled button appears...")
    enabled_btn = wdwait.until(
        EC.visibility_of_element_located((By.ID, 'hidden')))
    enabled_btn.click()
    print("waiting until enabled button disappears...")
    wdwait.until_not(EC.visibility_of_element_located((By.ID, 'hidden')))
    print("case 2 completed!")

    print("## Case 3: element_to_be_clickable")
    enabled_btn_id = "enable-button"
    driver.find_element_by_id(enabled_btn_id).click()
    print("waiting until Button button is clickable...")
    wdwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#disable')))
    print("case 3 completed!")

    print("## Case 4: element_to_be_clickable")
    check_btn_id = "checkbox"
    driver.find_element_by_id(check_btn_id).click()
    print("waiting until box is selected...")
    wdwait.until(EC.element_to_be_selected(
        (By.CSS_SELECTOR, '#ch')))  # this return True/False
    driver.find_element_by_css_selector("#ch").click()
    print("waiting until box is unchecked...")
    wdwait.until_not(EC.element_to_be_selected((By.CSS_SELECTOR, '#ch')))
    print("case 4 completed!")
Exemplo n.º 33
0
 def text_in_element(self, locator, _text):
     try:
         r = WebDriverWait(self.driver, 30, 1).until(EC.text_to_be_present_in_element(locator, _text))
         return r
     except:
         return False
Exemplo n.º 34
0
from selenium import webdriver
import math
import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))


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

# говорим Selenium проверять в течение 5 секунд, пока кнопка не станет кликабельной
WebDriverWait(browser, 12).until(
    EC.text_to_be_present_in_element((By.ID, 'price'), '10000 RUR'))
browser.find_element_by_css_selector('#book').click()

valel = WebDriverWait(browser, 5).until(
    EC.element_to_be_clickable((By.ID, "input_value")))
val = calc(int(valel.text))
browser.find_element_by_css_selector('#answer').send_keys(val)

browser.find_element_by_css_selector('#solve').click()
Exemplo n.º 35
0
 def wait_until_text_visible_by_xpath(self, xpath_locator, text_string):
     return self.wait().until(
         EC.text_to_be_present_in_element((By.XPATH, xpath_locator),
                                          text_string))
Exemplo n.º 36
0
 def assert_that_text_appears(self, css_selector, text):
     self.assert_wait(
         EC.text_to_be_present_in_element((By.CSS_SELECTOR, css_selector),
                                          text),
         "Text '%s' failed to appear in '%s'." % (text, css_selector))
Exemplo n.º 37
0
    def enter_concert(self):
        print('###打开浏览器,进入大麦网###')
        self.driver = webdriver.Firefox()  #默认火狐浏览器
        self.driver.maximize_window()
        self.login()  #先登录再说
        self.driver.refresh()
        try:
            locator = (By.XPATH,
                       "/html/body/div[1]/div/div[3]/div[1]/a[2]/div")
            element = WebDriverWait(self.driver, 3).until(
                EC.text_to_be_present_in_element(locator, self.usr_name))
            self.status = 1
            print("###登录成功###")
        except:
            self.status = 0
            print("###登录失败###")
        if self.status == 1:
            self.driver.find_elements_by_xpath(
                '/html/body/div[1]/div/div[4]/input')[0].send_keys(
                    self.name)  #搜索栏输入歌星
            self.driver.find_elements_by_xpath(
                '/html/body/div[1]/div/div[4]/div[1]')[0].click()  #点击搜索
            try:
                element = WebDriverWait(self.driver, 3).until(
                    EC.presence_of_element_located(
                        (By.ID, 'category_filter_id')))
                kinds = element.find_elements_by_tag_name('li')  #选择演唱会类别
            except Exception as e:
                print(e)
            for k in kinds:
                if k.text == '演唱会':
                    k.click()
                    break
            lists = self.driver.find_elements_by_id(
                'content_list')[0].find_elements_by_tag_name('li')  #获取所有可能演唱会
            titles = []
            links = []
            #注释的代码表示用图形界面手动选择演唱会,可以自行体会
            #        root = Tk()
            #        root.title("选择演唱会")
            #        v = IntVar()
            #        v.set(1)
            self.choose_result = 0
            #        def selection():
            #            self.choose_result=v.get()
            #            root.destroy()
            for li in lists:
                word_link = li.find_element_by_tag_name('h3')
                titles.append(word_link.text)
                temp_s = word_link.get_attribute('innerHTML').find('href') + 6
                temp_e = word_link.get_attribute('innerHTML').find(
                    'target') - 2
                links.append(
                    word_link.get_attribute('innerHTML')[temp_s:temp_e])
                if li.find_element_by_tag_name('h3').text.find(
                        self.place) != -1:  #选择地点正确的演唱会
                    self.choose_result = len(titles)
                    break

    #            b = Radiobutton(root,text = titles[-1],variable = v,value = len(titles),command=selection)
    #            b.pack(anchor = W)
    #        root.mainloop()
    #        while self.choose_result==0:
    #            sleep(1)
            self.url = "https:" + links[self.choose_result - 1]
            self.driver.get(self.url)  #载入至购买界面
            self.status = 2
            print("###选择演唱会###")
Exemplo n.º 38
0
def test_web_regressions(browser, tmpdir):
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver import ActionChains

    tmpdir = six.text_type(tmpdir)
    local = abspath(dirname(__file__))
    cwd = os.getcwd()

    os.chdir(tmpdir)
    try:
        machine_file = join(tmpdir, 'asv-machine.json')

        shutil.copyfile(join(local, 'asv-machine.json'), machine_file)

        values = [[x] * 2 for x in
                  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2]]
        dvcs = tools.generate_test_repo(tmpdir, values)
        repo_path = dvcs.path

        first_tested_commit_hash = dvcs.get_hash('master~14')

        conf = config.Config.from_json({
            'env_dir':
            join(tmpdir, 'env'),
            'benchmark_dir':
            join(local, 'benchmark'),
            'results_dir':
            join(tmpdir, 'results_workflow'),
            'html_dir':
            join(tmpdir, 'html'),
            'repo':
            repo_path,
            'dvcs':
            'git',
            'project':
            'asv',
            'matrix': {},
            'regressions_first_commits': {
                '.*': first_tested_commit_hash
            },
        })

        tools.run_asv_with_conf(conf,
                                'run',
                                'ALL',
                                '--bench=params_examples.track_find_test',
                                '--show-stderr',
                                '--quick',
                                _machine_file=machine_file)
        tools.run_asv_with_conf(conf, 'publish')
    finally:
        os.chdir(cwd)

    bad_commit_hash = dvcs.get_hash('master~9')

    with tools.preview(conf.html_dir) as base_url:
        get_with_retry(browser, base_url)

        regressions_btn = browser.find_element_by_link_text('Show regressions')
        regressions_btn.click()

        # Check that the expected links appear in the table
        regression_1 = browser.find_element_by_link_text(
            'params_examples.track_find_test(1)')
        regression_2 = browser.find_element_by_link_text(
            'params_examples.track_find_test(2)')
        bad_hash_link = browser.find_element_by_link_text(bad_commit_hash[:8])

        href = regression_1.get_attribute('href')
        assert '/#params_examples.track_find_test?' in href
        assert 'time=' in href

        # Sort the tables vs. benchmark name (PhantomJS doesn't allow doing it via actionchains)
        browser.execute_script("$('thead th').eq(0).stupidsort('asc')")
        WebDriverWait(browser, 5).until(
            EC.text_to_be_present_in_element(
                ('xpath', '//table[1]/tbody/tr[1]/td[1]'),
                'params_examples.track_find_test(1)'))

        # Check the contents of the table
        table_rows = browser.find_elements_by_xpath('//table[1]/tbody/tr')
        assert len(table_rows) == 2
        cols1 = [td.text for td in table_rows[0].find_elements_by_xpath('td')]
        cols2 = [td.text for td in table_rows[1].find_elements_by_xpath('td')]

        assert cols1[0] == 'params_examples.track_find_test(1)'
        assert cols2[0] == 'params_examples.track_find_test(2)'

        assert re.match(r'^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d+Z$', cols1[1])
        assert re.match(r'^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d+Z$', cols2[1])

        assert cols1[2:] == [
            bad_commit_hash[:8], '2.00x', '1.00', '2.00', 'Ignore'
        ]
        assert cols2[2:] == [
            bad_commit_hash[:8], '2.00x', '1.00', '2.00', 'Ignore'
        ]

        # Check that the ignore buttons work as expected
        buttons = [
            button for button in browser.find_elements_by_xpath('//button')
            if button.text == 'Ignore'
        ]
        buttons[0].click()

        # The button should disappear, together with the link
        WebDriverWait(browser, 5).until_not(EC.visibility_of(buttons[0]))
        WebDriverWait(browser, 5).until_not(EC.visibility_of(regression_1))

        table_rows = browser.find_elements_by_xpath('//table[1]/tbody/tr')
        assert len(table_rows) == 1

        # There's a second button for showing the links, clicking
        # which makes the elements reappear
        show_button = [
            button for button in browser.find_elements_by_xpath('//button')
            if button.text == 'Show ignored regressions...'
        ][0]
        show_button.click()

        regression_1 = browser.find_element_by_link_text(
            'params_examples.track_find_test(1)')
        WebDriverWait(browser, 5).until(EC.visibility_of(regression_1))

        table_rows = browser.find_elements_by_xpath('//table[2]/tbody/tr')
        assert len(table_rows) == 1

        # There's a config sample element
        pre_div = browser.find_element_by_xpath('//pre')
        assert "params_examples\\\\.track_find_test\\\\(1\\\\)" in pre_div.text

        # There's an unignore button that moves the element back to the main table
        unignore_button = [
            button for button in browser.find_elements_by_xpath('//button')
            if button.text == 'Unignore'
        ][0]
        unignore_button.click()

        browser.find_elements_by_xpath(
            '//table[1]/tbody/tr[2]')  # wait until the table has two rows

        table_rows = browser.find_elements_by_xpath('//table[1]/tbody/tr')
        assert len(table_rows) == 2

        # Check that a plot of some sort appears on mouseover.  The
        # page needs to be scrolled first so that the mouseover popup
        # has enough space to appear.
        regression_1 = browser.find_element_by_link_text(
            'params_examples.track_find_test(1)')

        y = regression_1.location['y']
        browser.execute_script('window.scrollTo(0, {0})'.format(y - 200))

        chain = ActionChains(browser)
        chain.move_to_element(regression_1)
        chain.perform()

        popover = browser.find_element_by_css_selector('div.popover-content')
        flotplot = browser.find_element_by_css_selector('canvas.flot-base')
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait


def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))


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

    WebDriverWait(browser, 12).until(
        EC.text_to_be_present_in_element(
            (By.ID, "price"),
            "$100"))  # Дождаться, когда цена дома уменьшится до 10000 RUR
    browser.find_element_by_id(
        'book').click()  # Нажать на кнопку "Забронировать"

    num = browser.find_element_by_id("input_value").text
    browser.find_element_by_tag_name("input").send_keys(calc(
        int(num)))  # Считаем значение и записываем в форму ввода
    browser.find_element_by_id("solve").click()

finally:
    # ожидание чтобы визуально оценить результаты прохождения скрипта
    time.sleep(10)
    # закрываем браузер после всех манипуляций
    browser.quit()
Exemplo n.º 40
0
from selenium import webdriver
import time
import math
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

try:
    def calc(x):
        return str(math.log(abs(12*math.sin(int(x)))))
    link = "http://suninjuly.github.io/explicit_wait2.html"
    browser = webdriver.Chrome()
    browser.get(link)
    button = WebDriverWait(browser, 15).until(
        EC.text_to_be_present_in_element((By.ID, "price"),"$100")
    )
    button = browser.find_element_by_class_name("btn-primary")
    button.click()

    x_element = browser.find_element_by_css_selector("#input_value")
    x = x_element.text
    y = calc(x)

    # Ваш код, который заполняет обязательные поля
    # Проверяется, что поле required + поиск по placeholder
    input1 = browser.find_element_by_css_selector("#answer")
    input1.send_keys(y)

    # Отправляем заполненную форму
    button = browser.find_element_by_css_selector("[type=submit]")
    button.click()
Exemplo n.º 41
0
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from time import sleep

chromedriver = '/usr/local/bin/ChromeDriver'
browser = webdriver.Chrome(executable_path=chromedriver)
browser.maximize_window()
browser.get('https://www.baidu.com')

'''
actionschains=ActionChains(browser)

more_products=browser.find_element_by_xpath('//a[contains(text(),更多产品)]')
actionschains.move_to_element(more_products).perform()
sleep(2)
'''

locator=browser.find_element_by_link_text('贴吧')
text=u'贴吧'
result = expected_conditions.text_to_be_present_in_element(locator,text)(browser)
print(result)

browser.close()







Exemplo n.º 42
0
 def see_element_with_text(self, text):
     WebDriverWait(self.driver, 10).until(ec.text_to_be_present_in_element((By.TAG_NAME, "body"), text))
Exemplo n.º 43
0
import math
import os
import time


def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))


try:
    browser = webdriver.Chrome()
    browser.get("http://suninjuly.github.io/explicit_wait2.html")
    button = browser.find_element_by_tag_name("button")
    browser.execute_script("return arguments[0].scrollIntoView(true);", button)
    button_price = WebDriverWait(browser, 15).until(
        EC.text_to_be_present_in_element((By.ID, "price"), '100'))
    button_book = browser.find_element_by_css_selector("#book")
    button_book.click()
    button_solve = browser.find_element_by_id("solve")
    browser.execute_script("return arguments[0].scrollIntoView(true);",
                           button_solve)
    x = browser.find_element_by_id("input_value")
    x = x.text
    y = calc(x)
    answer = browser.find_element_by_id("answer")
    answer.send_keys(y)
    button_solve.click()

finally:
    # успеваем скопировать код за 10 секунд
    time.sleep(10)
Exemplo n.º 44
0
# Задание - ждем нужный текст на странице
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from math import log, sin

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

# Ждем цены 10000 RUR и жмем забронировать
price = WebDriverWait(browser, 12).until(
    EC.text_to_be_present_in_element((By.ID, "price"), "10000 RUR"))
browser.find_element_by_id("book").click()

# Капча для роботов (task2_1_1.py)
x = browser.find_element_by_css_selector('[id = "input_value"]').text
browser.find_element_by_css_selector('[id = "answer"]').send_keys(
    str(log(abs(12 * sin(int(x))))))

# Отправляем заполненную форму
browser.find_element_by_id("solve").click()
Exemplo n.º 45
0
Shop = driver.find_element_by_link_text("Shop")
Shop.click()
driver.execute_script("window.scrollBy(0, 300);")
basket = driver.find_element_by_css_selector('#content > ul > li.post-181.product.type-product.status-publish.product_cat-html.product_tag-html.has-post-title.no-post-date.has-post-category.has-post-tag.has-post-comment.has-post-author.instock.taxable.shipping-taxable.purchasable.product-type-simple > a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart')
basket.click()
time.sleep(3)
addbasket = driver.find_element_by_css_selector('#content > ul > li.post-165.product.type-product.status-publish.product_cat-javascript.product_tag-javascript.product_tag-mastering.has-post-title.no-post-date.has-post-category.has-post-tag.has-post-comment.has-post-author.instock.downloadable.taxable.shipping-taxable.purchasable.product-type-simple > a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart')
addbasket .click()
basket1 = driver.find_element_by_css_selector('#wpmenucartli > a')
basket1.click()
time.sleep(3)
delete = driver.find_element_by_css_selector('#page-34 > div > div.woocommerce > form > table > tbody > tr:nth-child(1) > td.product-remove > a')
delete.click()
time.sleep(3)
Undo = driver.find_element_by_css_selector('#page-34 > div > div.woocommerce > div.woocommerce-message > a')
Undo.click()
element = driver.find_element_by_css_selector('#page-34 > div > div.woocommerce > form > table > tbody > tr:nth-child(1) > td.product-quantity > div > input')
element.clear()
quantity = driver.find_element_by_css_selector("#page-34 > div > div.woocommerce > form > table > tbody > tr:nth-child(1) > td.product-quantity > div > input")
quantity.send_keys("3")
UPDATEBASKET = driver.find_element_by_css_selector('#page-34 > div > div.woocommerce > form > table > tbody > tr:nth-child(3) > td > input.button')
UPDATEBASKET.click()
item = driver.find_element_by_css_selector('#page-34 > div > div.woocommerce > form > table > tbody > tr:nth-child(1) > td.product-quantity > div > input').get_attribute('value')
assert item == "3"
print(item)
time.sleep(3)
APPLYCOUPON = driver.find_element_by_css_selector('#page-34 > div > div.woocommerce > form > table > tbody > tr:nth-child(3) > td > div > input.button')
APPLYCOUPON.click()
Code = WebDriverWait(driver, 20).until(
    EC.text_to_be_present_in_element((By.CSS_SELECTOR, "#page-34 > div > div.woocommerce > ul"), "Please enter a coupon code."))
Exemplo n.º 46
0
    def test_check_gateway_activation_and_online(self):
        driver = self.driver
        print("Go to MRC Server Web - " + mrc_server)
        driver.get( mrc_server + "/login")
        
        try:
            print("Wait for login button ...")
            WebDriverWait(driver, 20, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR, "section.mx-login-content")))
            driver.save_screenshot(result_dir + "/CheckGatewayActivationAndOnline_firefox_login.log")
            #if self.is_element_present(By.CSS_SELECTOR, "section.mx-login-content"): break
        except:
            mrc_robot_uexit()

        try:
            print("Wait for remember me ...")
            WebDriverWait(driver, 10, 1).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "BODY"), "Remember Me"))
            #if re.search(r"^[\s\S]*Remember Me[\s\S]*$", driver.find_element_by_css_selector("BODY").text): break
        except:
            mrc_robot_uexit()

        try:
            print("try to Login ...")
            driver.find_element_by_xpath("//input[@type='text']").clear()
            driver.find_element_by_xpath("//input[@type='text']").send_keys(user_name)
            driver.find_element_by_xpath("//input[@type='password']").clear()
            driver.find_element_by_xpath("//input[@type='password']").send_keys(password)
            driver.find_element_by_xpath("//input[@value='Login']").click()
        except:
            mrc_robot_uexit()

        # Warning: waitForTextPresent may require manual changes
        try:
            print("wait for group ...")
            WebDriverWait(driver, 10, 1).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "BODY"), "Select or search group:"))
            print("wait for navbar ...")
            WebDriverWait(driver, 20, 1).until(EC.presence_of_element_located((By.ID, "mx-navbar-toggle")))
            print("Login Success!")
            print("Click navbar ")
            driver.find_element_by_id("mx-navbar-toggle").click()
            #if re.search(r"^[\s\S]*Select or search group:[\s\S]*$", driver.find_element_by_css_selector("BODY").text): break
        except:
            mrc_robot_uexit()

        try:
            print("Click GW MGMT")
            #WebDriverWait(driver, 5, 1).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "BODY"), "Gateway Management"))
            #WebDriverWait(driver, 10, 1).until(EC.text_to_be_present_in_element((By.XPATH, "//li[4]/a/span"), "Gateway Management"))

            #WebDriverWait(driver, 5, 1).until(EC.presence_of_element_located((By.XPATH, "//li[4]/a/span")))
            driver.find_element_by_xpath("//li[4]/a/span").click()
            print("Click GW MGMT success")
            #WebDriverWait(driver, 10, 1).until(EC.presence_of_element_located((By.XPATH, "//li[4]/a")))
            #driver.find_element_by_xpath("//li[4]/a").click()
            #if re.search(r"^[\s\S]*Gateway Management[\s\S]*$", driver.find_element_by_css_selector("BODY").text): break
        except:
            mrc_robot_uexit()

        # ERROR: Caught exception [ERROR: Unsupported command [getEval | 0 | ]]
        serStat = "Y"
        # ERROR: Caught exception [ERROR: Unsupported command [while | (${i} !=5) | ]]
        # Warning: waitForTextPresent may require manual changes
        #try:
            #print("Check Activation Key")
            #WebDriverWait(driver, 10, 1).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "BODY"), "Activation Key"))
            #print("Check Activation Key Success")
            #if re.search(r"^[\s\S]*Activation Key[\s\S]*$", driver.find_element_by_css_selector("BODY").text): break
        #except:
            #mrc_robot_uexit()

        #try:
            #print("Check mx-land")
            #WebDriverWait(driver, 5, 1).until(EC.presence_of_element_located((By.XPATH, "//div[@id='mx-landing']/div/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div/div/div/div[2]/table/tbody/tr/td[2]/span")))
            #print("Check mx-land success")
            #if self.is_element_present(By.XPATH, "//div[@id='mx-landing']/div/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div/div/div/div[2]/table/tbody/tr/td[2]/span"): break
        #except:
            #mrc_robot_uexit()
        print("Go to check Settings in Gateway List")
        driver.find_element_by_link_text("Settings").click()
        try:
            print("Wait State ...")
            WebDriverWait(driver, 10, 1).until(EC.presence_of_element_located((By.XPATH, "//div[2]/div/div/div[2]/table/tbody/tr/td[4]")))
            print("Check State success")
            driver.implicitly_wait(5)
            istat = driver.find_element_by_xpath("//div[2]/div/div/div[2]/table/tbody/tr/td[4]").text
            print("Item: " + serStat + "---" + istat)
        except:
            mrc_robot_uexit()

        # ERROR: Caught exception [ERROR: Unsupported command [getEval | 0 | ]]
        rStat = "Online"
        dev_num = 1
        # Goto Status tab
        driver.find_element_by_link_text("Status").click()
        # ERROR: Caught exception [ERROR: Unsupported command [while | (${i} !=5) | ]]
        # Warning: waitForTextPresent may require manual changes
        # Check Gateway Portal
        try:
            print("Wait Virtual IP")
            WebDriverWait(driver, 10, 1).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "BODY"), "Virtual IP"))
            
            portal_link = driver.find_element_by_xpath("//td[6]/span").text
            print("Gateway Portal : " + portal_link)
            #if re.search(r"^[\s\S]*Virtual IP[\s\S]*$", driver.find_element_by_css_selector("BODY").text): break
        except:
            mrc_robot_uexit()

        try:
            print("Wait something")
            WebDriverWait(driver, 10, 1).until(EC.presence_of_element_located((By.XPATH, "//td[2]/span")))
            #if self.is_element_present(By.XPATH, "//td[2]/span"): break
        except:
            mrc_robot_uexit()
        
        try:
            print("Wait Status ...")
            WebDriverWait(driver, 10, 1).until(EC.presence_of_element_located((By.XPATH, "//td[2]/span")))
            wstat = driver.find_element_by_xpath("//td[2]/span").text
            print("Item: " + rStat + "---" + wstat)
            if wstat == "Online":
                print("Gateway Status : "+ wstat + "\n")
                driver.save_screenshot(result_dir + "/CheckGatewayActivationAndOnline_firefox_status.log")
            else:
                mrc_robot_uexit()
                AssertionError("\nGateway Status : "+ wstat + "\n")
        except:
            mrc_robot_uexit()

        #try:
            #print("Wait Connected device ...")
            #WebDriverWait(driver, 10, 1).until(EC.presence_of_element_located((By.XPATH, "//td[4]/span")))
            #print("Get Connected device ...")
            #condev = driver.find_element_by_xpath("//td[5]")
            #print("Item: " + dev_num + "---" + condev.text)
        #except:
            #mrc_robot_uexit()

        #driver.find_element_by_css_selector("button.mx-btn.mx-btn-default").click()
        driver.save_screenshot(result_dir + "/CheckGatewayActivationAndOnline_firefox_end.log")
        driver.close()
Exemplo n.º 47
0
from selenium.webdriver.support.ui import Select


def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))


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

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

    # говорим Selenium проверять в течение 5 секунд, пока кнопка не станет кликабельной
    button = WebDriverWait(browser, 12).until(
        EC.text_to_be_present_in_element((By.CSS_SELECTOR, "#price"), '$100'))

    button = browser.find_element_by_css_selector("#book")
    button.click()

    x = int(browser.find_element_by_css_selector("#input_value").text)

    inputy = browser.find_element_by_css_selector("#answer")
    y = calc(x)
    inputy.send_keys(y)

    button = browser.find_element_by_css_selector("[type='submit']")
    button.click()

finally:
    # успеваем скопировать код за 30 секунд
Exemplo n.º 48
0
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome('./chromedriver')
driver.get('http://exercise.kingname.info/exercise_advanced_ajax.html')

try:
    WebDriverWait(driver, 30).until(
        EC.text_to_be_present_in_element((By.CLASS_NAME, "content"), '通关'))
except Exception as _:
    print('网页加载太慢,不想等了。')

element = driver.find_element_by_xpath('//div[@class="content"]')
print(f'异步加载的内容是:{element.text}')

driver.quit()

# html = driver.page_source
# print(html)
# input('按任意键结束。')

# element = driver.find_element_by_id("passwd-id") #如果有多个符合条件的,返回第一个
# element = driver.find_element_by_name("passwd") #如果有多个符合条件的,返回第一个
# element_list = driver.find_elements_by_id("passwd-id") #以列表形式返回所有的符合条件的element
# element_list = driver.find_elements_by_name("passwd") #以列表形式返回所有的符合条件的element
# comment = driver.find_element_by_xpath('//div[@class="content"]')
# print(comment.text)
#
# comment = driver.find_elements_by_xpath('//p[starts-with(@id, "content_")]')
Exemplo n.º 49
0
 def thread_get(self, proxy_idx):
     error = 0
     count = 0
     ip, port = self.proxy_list[proxy_idx]
     # service_args = [
     #             '--proxy={}:{}'.format(ip, port),
     #             '--proxy-type={}'.format("socks5"),
     #         ]
     # driver = webdriver.PhantomJS(service_args=service_args)
     chrome_ops = webdriver.ChromeOptions()
     chrome_ops.add_argument(
         '--proxy-server={}://{}:{}'.format("socks5", ip, port))
     driver = webdriver.Chrome(chrome_options=chrome_ops, executable_path="/usr/local/bin/chromedriver")
     driver.set_window_size(500, 400)
     driver.set_window_position(proxy_idx % 3 * 400, (proxy_idx // 3)*400)
     driver.get("http://www.google.com")
     max_wait = 20
     while True:
         # print("-----------------------------------")
         query, page, per_page = self.q_query.get()
         with self.lock:
             self.running += 1
         # input_field = driver.find_element(By.NAME, 'q')
         def find_visible_search_input(driver):
             input_field = driver.find_element(By.NAME, 'q')
             return input_field
         try:
             search_input = WebDriverWait(driver, max_wait).until(find_visible_search_input)
         except (TimeoutException, NoSuchElementException) as e:
             print('Proxy #{}: TimeoutException waiting for search input field: {}'.format(proxy_idx, e))
             error += 1
             with self.lock:
                 self.running -= 1
             self.q_query.put((query, page, self.per_page))
             if error >= 3:
                 with self.lock:
                     self.proxy_list[proxy_idx] = False
                 break
             else:
                 continue
         if search_input:
             search_input.clear()
             try:
                 search_input.send_keys(query + Keys.ENTER)
             except ElementNotVisibleException:
                 time.sleep(2)
                 search_input.send_keys(query + Keys.ENTER)
             try:
                 WebDriverWait(driver, 15).\
                     until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#navcnt td.cur'), str(1)))
             except TimeoutException as e:
                 print("Proxy #{} TimeoutException, can't load the results page, {}.".format(proxy_idx, e))
                 with self.lock:
                     self.running -= 1
                     self.proxy_list[proxy_idx] = False
                 break
             try:
                 html = driver.execute_script('return document.body.innerHTML;')
             except WebDriverException as e:
                 html = driver.page_source
             if html and len(html) > 20:
                 # print(len(html))
                 self.q_ans.put((query, page, parse_google(html, query)))
         # elif "Captcha" in html:
         #     error = 3
         #     self.q_query.put((query, page, self.per_page))
             else:
                 error += 1
                 self.q_query.put((query, page, self.per_page))
         with self.lock:
             self.running -= 1
         self.q_query.task_done()
         if error == 3:
             with self.lock:
                 # self.working_thread -= 1
                 self.proxy_list[proxy_idx] = False
             break
         count += 1
         if count % 50 == 0:
             sleep_time = random.randint(30, 60)
         elif count % 40 == 0:
             sleep_time = random.randint(20, 40)
         elif count % 30 == 0:
             sleep_time = random.randint(16, 21)
         elif count % 20 == 0:
             sleep_time = random.randint(13, 17)
         elif count % 10 == 0:
             sleep_time = random.randint(9, 14)
         elif count % 5 == 0:
             sleep_time = random.randint(8, 11)
         else:
             sleep_time = random.randint(5, 9)
         print("Proxy #{}, scraping keyword: {}, {} keywords completed,"
               " sleep for {} seconds".format(proxy_idx+1, query, count, sleep_time))
         time.sleep(sleep_time+random.random())
     print("Thread %s terminated due to proxy not working properly." % (proxy_idx+1,))
     driver.quit()
     with self.lock:
         self.working_thread -= 1
     if self.working_thread == 0:
         print("All threads terminated, please use new proxy and rerun")
Exemplo n.º 50
0
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import math
browser = webdriver.Chrome()

browser.get("http://suninjuly.github.io/explicit_wait2.html")

# говорим Selenium проверять в течение 5 секунд, пока кнопка не станет кликабельной
book_btn = '#book'
price = '#price'
num1 = 'input_value'
ansver = '#answer'
submit_btn = 'button[type="submit"]'
num1 = 'input_value'

# ждём понижения цены
WebDriverWait(browser, 20).until(
    EC.text_to_be_present_in_element((By.CSS_SELECTOR, price), "$100"))
browser.find_element_by_css_selector(book_btn).click()

# Завершаем бронирование
el1 = browser.find_element_by_id(num1)
element1 = el1.text
result = math.log(abs(12 * math.sin(int(element1))))
ansver = browser.find_element_by_css_selector(ansver)
ansver.send_keys(str(result))
browser.find_element_by_css_selector(submit_btn).click()
Exemplo n.º 51
0
    def test_cart(self):
        WebDriverWait(self.driver, 5).until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, "#box-most-popular")))

        quantity_cart = int(
            self.driver.find_element(By.CSS_SELECTOR, "#cart .quantity").text)

        while quantity_cart < 3:
            list_products = self.driver.find_elements(By.CSS_SELECTOR,
                                                      "#box-most-popular li")

            first_product = list_products[0]
            first_product.click()

            quantity_cart = int(
                self.driver.find_element(By.CSS_SELECTOR,
                                         "#cart .quantity").text)

            WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "#box-product .information")))

            list_order_trs = self.driver.find_elements(By.CSS_SELECTOR,
                                                       ".buy_now tr")
            if (len(list_order_trs) > 1):
                select = list_order_trs[0].find_element(
                    By.CSS_SELECTOR, "[name*='options[Size]']")
                self.driver.execute_script(
                    "arguments[0].selectedIndex = 1; arguments[0].dispatchEvent(new Event('change'))",
                    select)

            button_add_cart = self.driver.find_element(
                By.CSS_SELECTOR, ".buy_now [name='add_cart_product']")
            button_add_cart.click()

            new_quantity_cart = str(quantity_cart + 1)

            WebDriverWait(self.driver, 5).until(
                EC.text_to_be_present_in_element(
                    (By.CSS_SELECTOR, "#cart .quantity"), new_quantity_cart))

            quantity_cart = int(
                self.driver.find_element(By.CSS_SELECTOR,
                                         "#cart .quantity").text)

            logo = self.driver.find_element(By.CSS_SELECTOR,
                                            "#logotype-wrapper")
            logo.click()

        link_cart = self.driver.find_element(By.CSS_SELECTOR,
                                             "#cart .link[href*='checkout']")
        link_cart.click()

        # Кликаем в первую превьюшку, чтобы остановить вращение карусели с товарами
        list_preview_product = self.driver.find_elements(
            By.CSS_SELECTOR, ".shortcuts .shortcut")
        list_preview_product[0].click()

        items = self.driver.find_elements(
            By.CSS_SELECTOR, "#box-checkout-cart .viewport .items li")

        while len(items) != 0:
            table_order_summary = self.driver.find_element(
                By.CSS_SELECTOR, ".dataTable.rounded-corners")

            name_product_delete = items[0].find_element(
                By.CSS_SELECTOR, "a strong").text

            remove_button = items[0].find_element(By.CSS_SELECTOR,
                                                  "[name='remove_cart_item']")
            remove_button.click()

            WebDriverWait(self.driver,
                          10).until(EC.staleness_of(table_order_summary))

            table_order_summary_items = self.driver.find_elements(
                By.CSS_SELECTOR,
                ".dataTable.rounded-corners tr:not(.header) .item")
            item_still_exists = False
            for i in range(len(table_order_summary_items)):
                if table_order_summary_items[i].text == name_product_delete:
                    item_still_exists = True
                    break
            assert not item_still_exists, "Элемент после удаления остался в таблице"

            items = self.driver.find_elements(
                By.CSS_SELECTOR, "#box-checkout-cart .viewport .items li")
Exemplo n.º 52
0
# Открыть страницу http://suninjuly.github.io/explicit_wait2.html
# Дождаться, когда цена дома уменьшится до $100 (ожидание нужно установить не меньше 12 секунд)
# Нажать на кнопку "Book"
# Решить уже известную нам математическую задачу (используйте ранее написанный код) и отправить решение

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import math


def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))


driver = webdriver.Chrome()
try:
    driver.get('http://suninjuly.github.io/explicit_wait2.html')
    WebDriverWait(driver, 15).until(
        EC.text_to_be_present_in_element((By.ID, 'price'), '$100'))
    driver.find_element_by_id('book').click()
    y = calc(int(driver.find_element_by_id('input_value').text))
    driver.find_element_by_id('answer').send_keys(str(y))
    driver.find_element_by_id('solve').click()
    sleep(30)
finally:
    driver.quit()
Exemplo n.º 53
0
 def click_exit_login(self):
     """退出登录"""
     self.driver.find_element(*self.ck_sign_out_loc).click()
     WebDriverWait(self.driver, 10).until(EC.text_to_be_present_in_element(self.txt_PUNDIX_msg, u'YOUR DIGITAL ASSETS PASS'))
     return self.driver.find_element(*self.txt_PUNDIX_msg).text
Exemplo n.º 54
0
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
url = "https://www.baidu.com"
driver.get(url)

locator = ("name", "tj_trmap")
text = "地图"
result = EC.text_to_be_present_in_element(locator, text)(driver)  #判断字段是否存在
print(result)
Exemplo n.º 55
0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import math
browser = webdriver.Chrome()
link = "http://suninjuly.github.io/explicit_wait2.html"
browser.get(link)

WebDriverWait(browser, 12).until(EC.text_to_be_present_in_element((By.ID, "price"),'$100'))
browser.find_element_by_id("book").click()
x=int(browser.find_element_by_id("input_value").text)
answer = str(math.log(abs(12*math.sin(x))))
input1=browser.find_element_by_id("answer")
input1.send_keys(answer)
browser.find_element_by_id("solve").click()
assert True

Exemplo n.º 56
0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://www.speedtest.net/')

gobutton = driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div/div/div/div[2]/div[3]/div[1]/a')
gobutton.click()

try:
	WebDriverWait(driver, 120).until(EC.text_to_be_present_in_element((By.CLASS_NAME, "overall-progress"), 'Your speed test has completed.'))
	driver.implicitly_wait(10)
except:
	print("Took too long")

ele = driver.find_element_by_class_name('speedtest-container')

ele.screenshot("screenshot.png")
Exemplo n.º 57
0
def sign():
    log = open('C:/programming/buaa_ncov_auto/sign_at_home.log', 'a')
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

    chrome_options = Options()
    chrome_options.add_experimental_option("excludeSwitches",
                                           ["enable-logging"])
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    browser = webdriver.Chrome(options=chrome_options)
    browser.set_window_size(720, 1280)

    url = "https://app.buaa.edu.cn/site/ncov/xisudailyup"
    header = {
        'User-agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
    }
    browser.get(url)

    try:
        user = WebDriverWait(browser, 30).until(
            EC.element_to_be_clickable((By.TAG_NAME, "input")))
    finally:
        browser.save_screenshot('login.png')

    username = browser.find_element_by_tag_name('input')
    username.send_keys(pw.uni_user)

    password = browser.find_element_by_xpath("//input[@type='password']")
    password.send_keys(pw.uni_password)

    login_button = browser.find_element_by_css_selector('div.btn')

    browser.execute_script("$(arguments[0]).click()", login_button)

    try:
        element = WebDriverWait(browser, 30).until(
            EC.presence_of_element_located(
                (By.XPATH, "//div[@name='sfzx']/div/div[1]")))
    finally:
        browser.save_screenshot('loaded.png')

    sleep(1)

    # Check if already signed.
    if EC.text_to_be_present_in_element((By.CLASS_NAME, "footers"),
                                        "您已提交过信息")(browser):
        datee = time.asctime()
        print("%s already signed. " % (datee), file=log)
        print("%s already signed. " % (datee))
        log.flush()
        browser.quit()
        log.close()
        return

    # Check if it is too early for sign.
    if EC.text_to_be_present_in_element((By.CLASS_NAME, "footers"),
                                        "未到填报时间")(browser):
        datee = time.asctime()
        print("%s wait for sign, too early. " % (datee), file=log)
        print("%s wait for sign, too early. " % (datee))
        log.flush()
        browser.quit()
        log.close()
        return

    # Load geo info.
    browser.execute_script(
        "window.navigator.geolocation.getCurrentPosition=function(success){" +
        "var position = {\"coords\" : {\"latitude\": \"" + gi.lz_latitude +
        "\",\"longitude\": \"" + gi.lz_longitude + "\"}};" +
        "success(position);}")
    sleep(1)

    # 所在地点
    where = browser.find_element_by_name("area")
    where.click()
    sleep(1)
    browser.save_screenshot('geo.png')

    #今日体温范围
    body_temperature = browser.find_element_by_xpath(
        "//div[@name='tw']/div/div[2]")
    body_temperature.click()
    browser.save_screenshot('tw.png')

    # 是否在校
    not_at_school = browser.find_element_by_xpath(
        "//div[@name='sfzx']/div/div[2]")
    not_at_school.click()
    browser.save_screenshot('sfzx.png')

    #是否请假外出
    ask_for_leave = browser.find_element_by_xpath(
        "//div[@name='askforleave']/div/div[1]")
    ask_for_leave.click()
    browser.save_screenshot('askforleave.png')

    #今日是否返校住宿
    not_return_to_school = browser.find_element_by_xpath(
        "//div[@name='sffxzs']/div/div[2]")
    not_return_to_school.click()
    browser.save_screenshot('sffxzs.png')

    # #是否处于隔离期
    # not_at_quarantine = browser.find_element_by_xpath("//div[@name='sfcyglq']/div/div[2]")
    # not_at_quarantine.click()
    # sleep(0.5)
    # browser.save_screenshot('sfcyglq.png')

    #提交
    footers = browser.find_element_by_class_name('footers')
    footers.click()
    sleep(1)
    browser.save_screenshot('confirm.png')

    #确认
    confirm = browser.find_element_by_class_name('wapcf-btn-ok')
    confirm.click()
    sleep(1)
    browser.save_screenshot('signed.png')

    datee = time.asctime()

    print("%s signed successfully! " % (datee), file=log)
    print("%s signed successfully! " % (datee))
    log.flush()

    browser.quit()
    log.close()
Exemplo n.º 58
0
    def test_end_to_end(self):
        converter = Converter(self.driver)

        with pytest.allure.step('Ввод суммы'):
            # кликаем поле для ввода суммы
            converting_summ = converter.find(converter.summ)
            converting_summ.click()
            assert 'Не удалось найти и кликнуть в поле ввода суммы'

            # очищаем поле для ввода суммы
            converting_summ.clear()

            assert 'Не удалось очистить поле ввода суммы'

            # вводим сумму
            converting_summ.send_keys('1')
            assert 'Не удалось ввести сумму'

        with pytest.allure.step('Выбор опций'):
            # выбираем валюту, из которой конвертируем
            converterFrom = converter.find(converter.convFrom)
            converterFrom.click()
            assert 'Список валют "из" не открывается'

            # выбираем EUR
            eur = converter.find(
                "//select[@name='converterFrom']/../div/div/span[text()='EUR']"
            )
            eur.click()
            assert 'Не удалось выбрать валюту (EUR)'

            # выбираем валюту, в которую конвертируем
            converterTo = converter.find(converter.convTo)
            converterTo.click()
            assert 'Список валют "в" не открывается'

            # выбираем GBP
            gbp = converter.find(
                "//select[@name='converterTo']/../div/div/span[text()='GBP']")
            gbp.click()
            assert 'Не удалось выбрать валюту (GBP)'

            # в блоке "Источник" выбираем "Наличные"
            source = converter.find(converter.cash)
            source.click()
            assert 'Не удалось выбрать "Источник" - "Наличные"'

            # в блоке "Получение" выбираем "Выбрать наличные"
            destination = converter.find(converter.choose_cash)
            destination.click()
            assert 'Не удалось выбрать "Получение" - "Выбрать наличные"'

        with pytest.allure.step(
                'Вывод результата с помощью кнопки "Показать"'):
            # нажимаем "Показать"
            button = converter.find(converter.show_button)
            button.click()

            # ждем, когда появится блок с результатом
            try:
                WebDriverWait(self.driver, 10).until(
                    ec.text_to_be_present_in_element(
                        (By.XPATH, converter.result_to), '0,83'))
            except TimeoutException:
                raise Exception('Значение не получено')

            converterFrom_sel = converter.get_text(converter.convFrom_select)
            converterTo_sel = converter.get_text(converter.convTo_select)

            with pytest.allure.step('Проверка результата'):
                assert converterFrom_sel == 'EUR', 'Неверная валюта "из"'
                assert converterTo_sel == 'GBP', 'Неверная валюта "в"'
def wait_for_message():
    WebDriverWait(driver, 10).until(
        expected_conditions.text_to_be_present_in_element(
            (By.CLASS_NAME, "alert-info"), "Employee has deleted"))
Exemplo n.º 60
0
 def wait_until_text_visible_by_css(self, css_locator, text_string):
     return self.wait().until(
         EC.text_to_be_present_in_element((By.CSS_SELECTOR, css_locator),
                                          text_string))