Example #1
0
    def get_replay_helper(self, replay_id, background):
        if background:
            fast_forward_btn = self.driver.find_element_by_css_selector("[data-action='ff']") 
            # Iterate through up to MAX_GAME_LENGTH turns
            for i in range(MAX_GAME_LENGTH):
                fast_forward_btn.click()
                # Once we've skipped through at least 100 turns, check if the
                # battle has ended every 50 turns
                if i > 100 & i % 50 == 0:
                    log = self.driver.find_element_by_css_selector(".battle-log")
                    if "won the battle" in log.text:
                        return log.text 
            # If the game hasn't ended after MAX_GAME_LENGTH turns, throw an exception
            raise EndOfLogException("Failed to reach end of log file")                
        else:
            # Open the turn picking dialogue
            pick_turn_btn = self.driver.find_element_by_css_selector("[data-action='ffto']")
            pick_turn_btn.click()

            # Pick the last turn
            alert = Alert(self.driver)
            alert.send_keys(str(-1))
            alert.accept()      

            log = self.driver.find_element_by_css_selector(".battle-log")
            return log.text
def test_with_isolation_and_check(mocker):
    with mocker.patch('selenium.webdriver.remote.webdriver.WebDriver') as MockDriver:
        driver = MockDriver.return_value

        alert = Alert(driver)
        alert.accept()

        driver.execute.assert_called_with("acceptAlert")
    def test_pruebas_ini_sesion(self):
        driver = self.driver
        driver.get(self.base_url + "/#/VLogin")
        actions = ActionChains(self.driver)
        alert = Alert(self.driver)
        
########################  Contrasenha Invalida #################################################### 
        driver.find_element_by_id("fLogin_usuario").clear()
        driver.find_element_by_id("fLogin_usuario").send_keys("Test Usuario")
        driver.find_element_by_id("fLogin_clave").clear()
        driver.find_element_by_id("fLogin_clave").send_keys("bbbbbbbb")
        driver.find_element_by_id("conectate").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
########################  Usuario no Existente #################################################### 
        driver.find_element_by_id("fLogin_usuario").clear()
        driver.find_element_by_id("fLogin_usuario").send_keys("UsuarioNoExiste")
        driver.find_element_by_id("fLogin_clave").clear()
        driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa")
        driver.find_element_by_id("conectate").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
########################  Usuario Vacio #################################################### 
        driver.find_element_by_id("fLogin_clave").clear()
        driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa")
        driver.find_element_by_id("conectate").click()
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
########################  Clave Vacia #################################################### 
        driver.find_element_by_id("fLogin_usuario").clear()
        driver.find_element_by_id("fLogin_usuario").send_keys("Test Usuario")
        driver.find_element_by_id("conectate").click()
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
########################  Todo Vacio #################################################### 
        driver.find_element_by_id("conectate").click()
Example #4
0
def accept_alert(test):
    """
    Accept the alert
    """

    try:
        alert = Alert(test.browser)
        alert.accept()
    except WebDriverException:
        # PhantomJS is kinda poor
        pass
Example #5
0
def dismiss_alert(test):
    """
    Dismiss the alert
    """

    try:
        alert = Alert(test.browser)
        alert.dismiss()
    except WebDriverException:
        # PhantomJS is kinda poor
        pass
Example #6
0
def accept_alert(self):
    """
    Accept the alert.
    """

    try:
        alert = Alert(world.browser)
        alert.accept()
    except WebDriverException:
        # PhantomJS is kinda poor
        pass
Example #7
0
def dismiss_alert(self):
    """
    Dismiss the alert.
    """

    try:
        alert = Alert(world.browser)
        alert.dismiss()
    except WebDriverException:
        # PhantomJS is kinda poor
        pass
Example #8
0
def test_alert():
    driver = webdriver.Remote(
        desired_capabilities=DesiredCapabilities.CHROME,
        command_executor="http://%s:4444" % host
    )
    driver.get('http://nginx:8000')
    alert = Alert(driver)
    print alert.text
    assert 'Hello' in alert.text
    alert.accept()
    driver.get_screenshot_as_file('screenshot.png')
    driver.quit()
Example #9
0
 def wd_SEL_Alert(self, target, value=None):
     """
     Retrieve the message of a JavaScript alert generated during the previous action, or fail if there are no alerts. 
     Getting an alert has the same effect as manually clicking OK. If an alert is generated but you do not consume it 
     with getAlert, the next webdriver action will fail.
     @param target: the expected message of the most recent JavaScript alert
     @param value: <not used>
     @return: the message of the most recent JavaScript alert
     """
     alert = Alert(self.driver)
     text = alert.text.strip()
     alert.accept()
     return target, text
 def test_3(self):
     driver = self.driver
     driver.get(self.base_url + "/#/VLogin")
     actions = ActionChains(self.driver)
     alert = Alert(self.driver)
     
     driver.find_element_by_id("fLogin_usuario").clear()
     driver.find_element_by_id("fLogin_usuario").send_keys("Usuario")
     driver.find_element_by_id("fLogin_clave").clear()
     driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa")
     driver.find_element_by_id("conectate").click()
     time.sleep(1)
     driver.find_element_by_xpath("//a[@ng-show='idUsuario']").click()
     time.sleep(1)
     driver.find_element_by_xpath(".//*[@id='invisible_interno']/div/div[2]/div[2]").click()
     driver.find_element_by_xpath("//input[@placeholder='Buscar amigos']").clear()
     driver.find_element_by_xpath("//input[@placeholder='Buscar amigos']").send_keys('Usuario3')
     driver.find_element_by_id("btnHilos").click()
     driver.find_element_by_id("config").click()
     actions.send_keys(Keys.CONTROL)
     actions.send_keys('r')
     actions.perform()
     time.sleep(.5)
     driver.find_element_by_xpath("//a[contains(@ng-click,'VGrupo2')]").click()
     actions.send_keys(Keys.CONTROL)
     actions.send_keys('r')
     actions.perform()
     time.sleep(.5)
     driver.find_element_by_xpath("//input[@placeholder='Buscar amigos']").send_keys('Usuario3')
     driver.find_element_by_id("btnHilos").click()
     driver.find_element_by_id("config").click()
     actions.send_keys(Keys.CONTROL)
     actions.send_keys('r')
     actions.perform()
     time.sleep(.5)
     driver.get(self.base_url + "/#/VAdminContactos/Usuario")
     driver.find_element_by_xpath("(//a[contains(@ng-click,'AElimContacto1')])[2]").click()
     time.sleep(0.5)
     alert.accept()
     time.sleep(.5)
     actions.send_keys(Keys.CONTROL)
     actions.send_keys('r')
     actions.perform()
     time.sleep(.5)
     driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click()
     time.sleep(.5)
     driver.find_element_by_xpath("//a[@ng-click='ASalir(idUsuario)']").click()
     time.sleep(.5)   
Example #11
0
def stress_test(username, password, key, max_count):
    emailInput.send_keys(username)
    passwordInput.send_keys(password)
    loginButton.click()
    driver.get(chatUrl)
    time.sleep(3.5)
    alert = Alert(driver)
    alert.send_keys(key)
    alert.accept()
    message_input = driver.find_element_by_xpath("//*[@id='messageInput']")
    send_button = driver.find_element_by_xpath("//*[@id='sendButton']")
    count = 1
    while count <= max_count:
        message_input.send_keys("This is Message number " + str(count))
        send_button.click()
        clear()
        print("Sending message " + str(count) + " / " + str(max_count))
        count += 1
Example #12
0
def payment(driver):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,   #신용카드 선택
        "//*[@id='content']/form/div/div[2]/div/div[2]/div[1]/div/div/div/div/div[3]/div/label/p"
            ))).click()
    driver.find_element_by_xpath( #개인정보 제 3자 제공동의
        "//*[@id='chk-order-agree']"
    ).click()

    driver.find_element_by_xpath( #쿠폰함 클릭
        "//*[@id='btn-modal-coupon']"
    ).click()

    time.sleep(2)
    CoupCode = driver.find_element_by_xpath(
        "//*[@id='coupon-available']/div/div/div/div/div[1]/div/div/div[1]/div[2]/span"
    ).text
    if CoupCode == "USS7000":  #만약에 쿠폰 코드가 맞다면 쿠폰 사용하기 클릭
        driver.find_element_by_xpath(
            "//*[@id='coupon-available']/div/div/div/div/div[1]/div"
        ).click()
    driver.find_element_by_xpath(  #쿠폰 적용하기
        "//*[@id='btn-apply-coupon']"
         ).click()
    time.sleep(2)
    Alert(driver).accept()
    print("Coupon is applied")

    #포인트 사용
    time.sleep(3)
    driver.find_element_by_xpath(
        "//*[@id='order-point-form']/div[2]/button"
    ).click()


   #구매버튼
    WebDriverWait(driver, 2)
    driver.find_element_by_xpath("//*[@id='btn-order-pay']").click()
Example #13
0
 def download_wait(self, p2):
     count3 = 0
     while True:
         try:
             self.get_html_df()
             temp_df = self.temp_df
             Alert(self.driver).text
             alert = self.driver.switch_to.alert
             alert.accept()
             self.log.append(', '.join(temp_df.iloc[i, 1:4].values))
         except:
             if len([
                     j for j in os.listdir(self.download_dir)
                     if p2.findall(j)
             ]) >= 1:
                 time.sleep(1)
                 count3 += 1
                 if count3 > 30:
                     self.log.append(', '.join(
                         temp_df.iloc[i, 1:4].values))
                     break
             else:
                 time.sleep(1)
                 break
Example #14
0
 def withdrawal_request(self):
     sleep(2)
     self.methods.wait_and_find_element_by_xpath_and_move(
         lk_conf.banking_section_xpath).click()
     self.methods.wait_and_find_element_by_xpath(
         lk_conf.withdrawal_request_xpath).click()
     self.count_request = len(
         self.methods.wait_and_find_elements_by_xpath(
             lk_conf.count_request_xpath))
     if self.count_request == 1:
         pass
     else:
         self.text_del = self.methods.wait_and_find_element_by_xpath(
             lk_conf.text_del_xpath).text
         if self.text_del == lk_conf.exp_text_for_del:
             self.methods.wait_and_find_element_by_xpath(
                 lk_conf.link_for_delete).click()
             Alert(self.driver).accept()
     self.methods.wait_and_find_element_by_xpath_and_move(
         lk_conf.data_type_visamaster_xpath).click()
     self.methods.wait_and_find_element_by_id(
         lk_conf.input_sum_request_id).send_keys(lk_conf.sum_small)
     self.methods.wait_and_find_element_by_id(
         lk_conf.button_request_id).click()
Example #15
0
def test_100caseWrong():
    for i in range(0, 100):
        # browser.implicitly_wait(10)

        browser.get("http://*****:*****@gmail.com")
        # fullname wrong
        name = names.get_full_name()
        browser.find_element_by_id("fullname").send_keys(name)
        # phone number
        browser.find_element_by_id("phone").send_keys(phoneran())
        # genarate password
        password = genaratePass()
        browser.find_element_by_id("pass").send_keys(password + "@" + "#" +
                                                     "1" + "a")

        browser.find_element_by_id("re_pass").send_keys(password + "@" + "#" +
                                                        "1" + "a")
        browser.find_element_by_xpath(
            "/html/body/section/div/div/div[1]/form/div[6]/div/label/span"
        ).click()
        sleep(1)

        browser.find_element_by_id("signup").click()
        Alert(browser).accept()
        """
        display all filed
        """
        # print(str(i) + " mail: " + "leduchoa" + (str(a)) + "@gmail.com")
        print(name)
        # print(phoneran())
        print(password)
Example #16
0
def test_copy_product_in_catalog(driver, fixture_authorization_admin):
    """Тест копирует под админом  продукт в каталоге"""
    # открываем каталог и заходим в Products
    driver.find_element_by_id("menu-catalog").click()
    ActionChains(driver).pause(0.5).perform()
    driver.find_element_by_link_text("Products").click()
    # указываем значения для поиска в форме фильтра: наименование продукта
    filter_product_name = driver.find_element_by_id("input-name")
    filter_product_name.click()
    filter_product_name.send_keys("HP LP3065")
    driver.find_element_by_id("button-filter").click()
    # находим и записываем в список все checkbox в списке, устанавливаем первый,
    # запоминаем количество продуктов с данным наименованием
    checkbox = driver.find_elements_by_css_selector(
        CatalogProductPage.checkbox_in_productList)
    count_product = len(checkbox)
    checkbox[0].click()
    # нажимаем кнопку копировать, проверям наличие сообщение об успешной операции, закрываем сообщение
    driver.find_element_by_css_selector(
        CatalogProductPage.button_copy_product).click()
    ActionChains(driver).pause(0.5).perform()
    driver.find_element_by_css_selector(CatalogProductPage.mess_by_product)
    driver.find_element_by_css_selector(
        CatalogProductPage.button_close_mess).click()
    # находим и записываем в список все checkbox в списке, проверяем, что количество продукта увеличилось на 1
    checkbox_after = driver.find_elements_by_css_selector(
        CatalogProductPage.checkbox_in_productList)
    count_product_after = len(checkbox_after)
    count_product_after == count_product + 1
    # выбираем послений продукт и удаляем его, подтверждаем удаление, проверям наличие сообщение об успешной операции
    checkbox_after[-1].click()
    driver.find_element_by_css_selector(
        CatalogProductPage.button_delete_product).click()
    Alert(driver).accept()
    ActionChains(driver).pause(0.5).perform()
    driver.find_element_by_css_selector(CatalogProductPage.mess_by_product)
Example #17
0
def test_alert():
    log = Log("UI测试").get_logger()
    driver = webdriver.Firefox()
    driver.set_window_size(960, 540)  # 设置窗口大小
    driver.get('http://sahitest.com/demo/promptTest.htm')

    time.sleep(2)
    driver.find_element_by_name('b1').click()

    # a1 = driver.switch_to.alert  # 通过switch_to.alert切换到alert
    a1 = Alert(driver)  # 直接实例化Alert对象
    time.sleep(2)
    log.info(a1.text)  # 获取alert文本内容,对有信息显示的alert框

    a1.send_keys('send some words to alert!')  # 往prompt型alert中传入字符串
    time.sleep(2)
    a1.accept()  # 等同于点击“确认”或“OK”
    # a1.dismiss() # 等同于点击“取消”或“Cancel”
    log.info(driver.find_element_by_name('t1').get_attribute('value'))

    driver.quit()
Example #18
0
def type_message_and_get_prompt_text_and_close_prompt(context):

    try:
        # wait for Prompt to be displayed
        context.driver.wait.until(EC.alert_is_present())

        # store Prompt in a variable for reuse
        alert = Alert(context.driver)

        # type a message
        alert.send_keys("Anna")

        # store the Prompt text in a variable
        prompt_text = alert.text

        print(f'Prompt shows following message: ' + prompt_text)

        # press the OK button to accept Prompt
        alert.accept()
        print("Prompt accepted")
    except TimeoutException:
        print("No Prompt")
Example #19
0
def Login(self, driver, id, pw):
    try:
        driver.get(
            'https://crf.cau.ac.kr/2016/pages/reservation/view.php?eNum=35&searchCampus=1'
        )

        #로그인 팝업 버튼 클릭
        driver.find_element_by_class_name('login_popup_open').click()

        #ID, PW 필드 채우기
        driver.find_element_by_id('memberId').send_keys(id)
        driver.find_element_by_id('memberPwd').send_keys(pw)

        #로그인 버튼 클릭
        driver.find_element_by_class_name('btn_login').click()

        popup = Alert(driver)
        if '오류' in popup.text:
            self.signal_AddLogMessage.emit(popup.text)
            popup.accept()
            driver.quit()
            self.signal_StopFunction.emit()
        else:
            popup.accept()
            self.signal_AddLogMessage.emit("로그인 완료.")
            driver.find_element_by_xpath(
                '//*[@id="main_contents"]/div/div[3]/div[1]/div[1]/div[2]/div[1]/ul/li[3]/a/div[4]'
            ).click()  #장비선택
            driver.find_element_by_xpath(
                '/html/body/div[3]/div/div/div[2]/a').click()  #예약하기버튼
            driver.switch_to_window(driver.window_handles[-1])  #새창으로 드라이버 변경
            time.sleep(3)

    except:
        driver.quit()
        self.signal_StopFunction.emit()
        return
 def accept(self):
     self.standby()
     self.standby()
     self.standby()
     Alert(self.driver).accept()
Example #21
0
 def alert_text(self):
     alert = Alert(self.browser_opr.driver)
     return alert.text
Example #22
0
 def alert_send_keys(self, keys):
     '''在确认框中输入值'''
     Alert(self.driver).send_keys(keys)
Example #23
0
from selenium.webdriver import Firefox
from time import sleep
from selenium.webdriver.common.alert import Alert

browser = Firefox()

browser.get('http://selenium.dunossauro.live/aula_11_a')

sleep(1)

browser.find_element_by_id('alert').click()

alerta = Alert(browser)

alerta.accept() # confirma, clicka no ok
Example #24
0
def accept_alert(step):
    Alert(world.browser).accept()
Example #25
0
def accept_alert(browser):
    try:
        alert = Alert(browser)
        alert.accept()
    except WebDriverException:
        pass
Example #26
0
File: ice.py Project: MrSimonC/ICE
 def add_user(self, details):
     """
     Add a single user into ICE
     Assumes login() has been called
     details = {'firstName': '', 'surname': '', 'username': '', 'description': '', 'role': '', 'location': '', 'newPassword: ''}
     Returns string: comment of what happened
     """
     try:
         self.driver.switch_to.default_content()   # Jump to the top of the frames hierachy
         self.driver.find_element_by_id('a151').click()   # Add/Edit user button
         wait = WebDriverWait(self.driver, 10)
         wait.until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'Right')))
         wait.until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'appFrame')))
         # Add new user menu
         self.driver.find_element_by_id('AddButton').click()
         self.driver.find_element_by_id('usernameTextBox').send_keys(details['username'])
         self.driver.find_element_by_id('PasswordTextBox').send_keys(details['newPassword'])
         self.driver.find_element_by_id('ConfirmPasswordTextBox').send_keys(details['newPassword'])
         if not self.driver.find_element_by_id('ChangePasswordCheckBox').is_selected():   # Should always be unticked on load
             self.driver.find_element_by_id('ChangePasswordCheckBox').click()
         self.driver.find_element_by_id('FullnameTextBox').send_keys(details['firstName'] + ' ' + details['surname'])
         self.driver.find_element_by_id('InitialsTextbox').send_keys(details['firstName'][:1] + details['surname'][:1])
         self.driver.find_element_by_id('DescriptionTextBox').send_keys(details['description'])  # Description/Job title
         Select(self.driver.find_element_by_id('RoleList')).select_by_visible_text(details['role'])  # Role dropdown
         # Locations Profile
         wait.until(EC.element_to_be_clickable((By.ID, 'imgLP')))
         self.driver.find_element_by_id('imgLP').click()
         Select(self.driver.find_element_by_id('LocationListBox')).select_by_visible_text(details['location'])  #All Locations dropdown
         self.driver.find_element_by_id('AddButton').click()
     except:
         return "There was a problem filling in the page. Can you check the role/location etc?"
     try:
         self.driver.find_element_by_id('btnCommand').click()     # Save user
         time.sleep(1)
         # Alert will display if a duplicate is found in the system
         alert = Alert(self.driver)
         alertText = alert.text
         alert.accept()
         wait.until(EC.element_to_be_clickable((By.ID, 'btnCommand')))   # Wait for Save User button
         self.driver.find_element_by_id('btnGoToIndex').click()
         if alertText[:13] == "Create failed" and alertText[-30:] == "already exists; cannot create.":
             return "Duplicate person found in the system"
         else:
             return alertText
     except NoAlertPresentException:
         # If you have a success message
         try:
             if self.driver.find_element_by_id('messageDisplay').text.strip() == \
                 'The user has been successfully updated.'\
                 or self.driver.find_element_by_id('messageDisplay').text.strip() == \
                     'The user has been successfully added.':
                 return 'User added successfully'
             else:
                 return self.driver.find_element_by_id('messageDisplay').text.strip()
         except NoSuchElementException:
             # You are now stuck on the page unable to save with an error (usually unrecoverable for add user)
             # Password problem?
             try:
                 if self.driver.find_element_by_id('PasswordValidator').text == 'You have used this password before in your last three passwords.':
                     return "Couldn't save the user as password has been used before."
                 else:
                     return self.driver.find_element_by_id('PasswordValidator').text
             except NoSuchElementException:
                 # Location correction
                 try:
                     if self.driver.find_element_by_id('spanLocationError').text == "There must be at least one location in the user's profile.":
                         Select(self.driver.find_element_by_id('LocationListBox')).select_by_visible_text(details['location'])  #All Locations dropdown
                         self.driver.find_element_by_id('AddButton').click()
                         self.driver.find_element_by_id('btnCommand').click()     # Save user
                         time.sleep(1)
                         try:  # If you have a success message
                             if self.driver.find_element_by_id('messageDisplay').text.strip() == "The user has been successfully updated.":
                                 return "Success (& location updated)"
                         except NoSuchElementException:
                             pass
                 except:
                     pass
         return "Couldn't save the user for some reason I can't determine."
Example #27
0
def dismiss_alert(browser):
    try:
        alert = Alert(browser)
        alert.dismiss()
    except WebDriverException:
        pass
Example #28
0
        '//*[@id="s_year"]/option[text()="2019"]').click()
    time.sleep(1)
    chrome.find_element_by_xpath(
        '//*[@id="s_month"]/option[text()="4"]').click()
    time.sleep(1)
    chrome.find_element_by_xpath(
        '//*[@id="s_day"]/option[text()="30"]').click()
    time.sleep(1)
    chrome.find_element_by_xpath(
        '//*[@id="s_hour"]/option[text()="12 (오후00)"]').click()
    time.sleep(1)

    # 조회하기 버튼 클릭
    mouse = webdriver.ActionChains(chrome)
    mouse.move_to_element(findbtn).click().perform()
    time.sleep(3)

    # alert 대화상자 처리

    Alert(chrome).accept()
    time.sleep(3)

    # 예매페이지가 잘 보이도록 페이지를 아래로 스크롤 함
    chrome.execute_script('scrollTo(0,550)')
    time.sleep(5)

except Exception as ex:
    print(ex, sys.exc_info()[-1].tb_lineno)
finally:
    chrome.quit()
Example #29
0
        def unmask():
            global excel
            global cache

            def _pop_up_um(event):
                if str(um_resultT.set(um_resultT.focus(), "#3")):
                    webbrowser.open("https://service.epost.go.kr/trace.RetrieveDomRigiTraceList.comm?sid1=" + str(
                        um_resultT.set(um_resultT.focus(), "#3")) + "&displayHeader=N")



            if not fileE.get():
                messagebox.showinfo("Error!", "명단 파일을 첨부하세요.")
            elif not sheetCBox.get():
                messagebox.showinfo("Error!", "해당 시트를 찾을 수 없습니다.")
            elif not nmcolCBox.get():
                messagebox.showinfo("Error!", "해당 열을 불러올 수 없습니다.")
            else:
                um_resultC = tk.Toplevel(dataC)
                um_resultC.title("마스킹 해제 결과")
                um_resultC.geometry("400x330+465+300")
                um_resultC.resizable(False, False)
                um_resultC.lift()
                um_resultT = tkinter.ttk.Treeview(um_resultC, columns=["", "", "", "", ""], height=14)
                um_resultT.grid(column=0, columnspan=2, row=0)
                um_resultT.yview()
                um_resultT["show"] = "headings"
                um_resultT.column("#1", width=30, anchor="center")
                um_resultT.heading("#1", text="#", anchor="center",
                                   command=lambda: _sort_column(um_resultT, "#1", False))
                um_resultT.column("#2", width=45, anchor="center")
                um_resultT.heading("#2", text="성명", anchor="center",
                                   command=lambda: _sort_column(um_resultT, "#2", False))
                um_resultT.column("#3", width=120, anchor="center")
                um_resultT.heading("#3", text="등기번호", anchor="center",
                                   command=lambda: _sort_column(um_resultT, "#3", False))
                um_resultT.column("#4", width=110, anchor="center")
                um_resultT.heading("#4", text="수령인/처리현황", anchor="center",
                                   command=lambda: _sort_column(um_resultT, "#4", False))
                um_resultT.column("#5", width=92, anchor="center")
                um_resultT.heading("#5", text="비고", anchor="center",
                                   command=lambda: _sort_column(um_resultT, "#5", False))
                um_resultT.bind('<<TreeviewOpen>>', _pop_up_um)
                um_resultT.tag_configure('success', background='#B7F0B1')
                um_resultT.tag_configure('fail', background='#F15F5F')
                um_resultT.tag_configure('alert', background='#F2CB61')
                um_toexcel = tk.Button(um_resultC, text="to Excel", padx=175, command=lambda: _to_excel(um_resultT, True))
                um_toexcel.grid(column=0, columnspan=2, row=1)

                sheet = excel[sheetCBox.get()]
                index = 0
                s_cnt = 0
                a_cnt = 0
                f_cnt = 0
                n_data = []
                s_list = []
                nm_col = cache[nmcolCBox.current()].column
                nm_row = cache[nmcolCBox.current()].row
                if not n_iv.get():
                    nm_row += 1
                for i in range(nm_row, sheet.max_row + 1):
                    n_data += [sheet[i][nm_col - 1].value]
                try:
                    for tv_nm in totalT.get_children():
                        index += 1
                        swt = False
                        driver = webdriver.Ie('IEDriverServer.exe')
                        webdriver.IeOptions()
                        driver.get(
                            'https://service.epost.go.kr/trace.RetrieveDomRigiTraceList.comm?sid1=' + tv_nm + '&displayHeader=N')
                        main_window_handle = driver.current_window_handle
                        driver.execute_script("fnPopupMaskingSolv()")
                        for handle in driver.window_handles:
                            if handle != main_window_handle:
                                driver.switch_to.window(handle)
                                break
                        for ex_nm in n_data:
                            if ex_nm:
                                msk_nm = ex_nm[0:1] + "*" + ex_nm[2:]
                                if totalT.set(tv_nm, "#2") == msk_nm:
                                    driver.execute_script('SetExpCookie("TraceCnt","0",10);')
                                    elem = driver.find_element_by_name('senderNm_masking')
                                    elem.send_keys(sndE.get()[1])
                                    elem = driver.find_element_by_name('receverNm_masking')
                                    elem.send_keys(ex_nm[1])
                                    driver.execute_script("return verifyNms(event);")
                                    try:
                                        WebDriverWait(driver, 10).until(EC.alert_is_present())
                                        Alert(driver).accept()
                                        continue
                                    except:
                                        um_pnum = tv_nm
                                        um_status = totalT.set(tv_nm, "#3")
                                        swt = True
                                        if n_data.count(ex_nm) > 1:
                                            um_resultT.insert("", "end", text="",
                                                              values=[index, ex_nm, um_pnum, um_status, "동명이인 존재"],
                                                              iid=index, tags=('alert',))
                                            a_cnt += 1
                                        elif ex_nm in s_list:
                                            for um_list in um_resultT.get_children():
                                                if um_resultT.set(um_list, "#2") == ex_nm:
                                                    um_resultT.set(um_list, "#5", "수신인 중복")
                                                    um_resultT.item(um_list, tags=('alert',))
                                                    s_cnt -= 1
                                                    a_cnt += 1
                                            um_resultT.insert("", "end", text="",
                                                              values=[index, ex_nm, um_pnum, um_status, "수신인 중복"],
                                                              iid=index, tags=('alert',))
                                            a_cnt += 1
                                        else:
                                            um_resultT.insert("", "end", text="",
                                                              values=[index, ex_nm, um_pnum, um_status, ""], iid=index,
                                                              tags=('success',))
                                            s_cnt += 1
                                            s_list += [ex_nm]

                                        driver.switch_to.window(main_window_handle)
                                        if p_iv.get():
                                            driver.execute_script("window.print();")
                                            try:
                                                WebDriverWait(driver, 10).until(EC.alert_is_present())
                                                Alert(driver).accept()
                                                time.sleep(5)
                                                driver.close()
                                                break
                                            except:
                                                print("print error")
                                        else:
                                            driver.close()
                                            break
                        if not swt:
                            um_resultT.insert("", "end", text="",
                                              values=[index, totalT.set(tv_nm, "#2"), totalT.set(tv_nm, "#1"),
                                                      totalT.set(tv_nm, "#3"), "성명 불일치"], iid=index, tags=('fail',))
                            f_cnt += 1
                            driver.close()
                            driver.switch_to.window(main_window_handle)
                            driver.close()

                    messagebox.showinfo("작업 완료", "성공: " + str(s_cnt) + " 경고: " + str(a_cnt) + " 실패: " + str(f_cnt))
                except:
                    messagebox.showinfo("Error!", "작업 도중 예외가 발생하였습니다.")
Example #30
0
    def crawling(self, input_data):
        temp_array = input_data.decode('ascii').split('#')  # bytes
        input_data = temp_array[0]

        # 해피머니 상품권 사용여부조회
        if input_data == 'happy_money_gift_num':
            if self.driver_happy.current_url != 'http://www.happymoney.co.kr/svc/card/useCardSearch.hm':
                crawling_value: str = 'happy_money_gift_num_error'
                return crawling_value

            pin1: str = temp_array[1]
            pin2: str = temp_array[2]
            pin3: str = temp_array[3]
            pin4: str = temp_array[4]
            pinAuth: str = temp_array[5]

            print(pin1)

            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('pinNumber1').send_keys(' ')
            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('pinNumber1').send_keys('')
            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('pinNumber1').send_keys('')
            # 핀번호 입력
            for pin in pin1:
                self.driver_happy.find_element_by_id('pinNumber1').send_keys(
                    pin)
                time.sleep(0.1)  # 조회 임의 대기시간

            self.driver_happy.find_element_by_id('pinNumber2').send_keys('')
            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('pinNumber2').send_keys('')
            for pin in pin2:
                self.driver_happy.find_element_by_id('pinNumber2').send_keys(
                    pin)
                time.sleep(0.1)  # 조회 임의 대기시간

            self.driver_happy.find_element_by_id('pinNumber3').send_keys('')
            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('pinNumber3').send_keys('')
            for pin in pin3:
                self.driver_happy.find_element_by_id('pinNumber3').send_keys(
                    pin)
                time.sleep(0.1)  # 조회 임의 대기시간

            self.driver_happy.find_element_by_id('pinNumber4').send_keys('')
            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('pinNumber4').send_keys('')
            for pin in pin4:
                self.driver_happy.find_element_by_id('pinNumber4').send_keys(
                    pin)
                time.sleep(0.1)  # 조회 임의 대기시간

            self.driver_happy.find_element_by_id('printDate').send_keys('')
            time.sleep(0.1)  # 조회 임의 대기시간
            self.driver_happy.find_element_by_id('printDate').send_keys('')
            for pin in pinAuth:
                self.driver_happy.find_element_by_id('printDate').send_keys(
                    pin)
                time.sleep(0.1)  # 조회 임의 대기시간

            self.driver_happy.find_element_by_id('usageStatusCheck').click()

            ar = Alert(self.driver_happy)
            alertText = ar.text
            print(alertText)
            time.sleep(1)  # 조회 임의 대기시간
            ar.accept()

            # 미사용
            if alertText == '발행일/인증번호를 확인하세요':
                crawling_value: str = 'happy_money_gift_num_none'
                return crawling_value
            else:
                crawling_value: str = 'happy_money_gift_num_use'
                return crawling_value

        # =========================================================================

        # 북앤 라이프 도서 상품권 pin번호 조회
        if input_data == 'book_and_life_book_pin':
            pin1 = temp_array[1]
            pin2 = temp_array[2]
            pin3 = temp_array[3]
            pin4 = temp_array[4]
            pinAuth = temp_array[5]

            self.driver.find_element_by_id('radio1_gcct').click()  # 라디오 선택
            self.driver.find_element_by_id('selectType1').click()  # 라디오 선택

            # 핀번호 입력
            self.driver.find_element_by_id('PIN1').send_keys("8643")
            self.driver.find_element_by_id('PIN2').send_keys("9129")
            self.driver.find_element_by_id('PIN3').send_keys("2241")
            self.driver.find_element_by_id('PIN4').send_keys("4601")

            # 인증번호 입력
            self.driver.find_element_by_id('pinAuthNum').send_keys("4824")

            # 상품권 조회
            self.driver.find_element_by_id('useConfirmSelect').click()
            time.sleep(3)  # 조회 임의 대기시간

            req = self.driver.page_source
            soup = BeautifulSoup(req, "html.parser")
            price1 = soup.find('td', id="tdPrice1").get_text()
            price3 = soup.find('td', id="tdPrice3").get_text()
            if price1 != "" and price3 != "":  # 상품권 발행이 올바른 상태이고
                if price1 == price3:  # 액면금액과 현재잔액과 일치할 경우
                    crawling_value: str = 'book_and_life_book_pin_use'
                    return crawling_value
                else:  # 일치하지 않을 경우
                    crawling_value: str = 'book_and_life_book_pin_none'
                    return crawling_value

            ar = Alert(self.driver)
            alertText = ar.text
            print(alertText)
            time.sleep(1)  # 조회 임의 대기시간
            ar.accept()

            # 미사용
            if alertText == '고객님, 상품권 번호가 잘못되었거나, 이미 사용된 것 같습니다. 계속 발생하면 고객센터(1544-5111)로 연락 부탁 드려도 될까요?' or alertText == '발행일/인증번호를 확인하세요' or alertText == '핀번호/바코드를 확인하세요':
                crawling_value: str = 'book_and_life_book_pin_none'
                return crawling_value

        # 북앤 라이프 도서 상품권 고유 번호 조회
        if input_data == 'book_and_life_book_inherence':
            uniqNum = temp_array[1]

            self.driver.find_element_by_id('radio1_gcct').click()  # 라디오 선택
            self.driver.find_element_by_id('selectOnlyNum').click()  # 라디오 선택

            # 상품권 고유 번호 입력
            self.driver.find_element_by_id('uniqNum').send_keys(uniqNum)

            # 상품권 조회
            self.driver.find_element_by_id('useConfirmSelect').click()
            time.sleep(3)  # 조회 임의 대기시간

            ar = Alert(self.driver)
            alertText = ar.text
            print(alertText)
            ar.accept()

            # 미사용
            if alertText == '고객님, 상품권 번호가 잘못되었거나, 이미 사용된 것 같습니다. 계속 발생하면 고객센터(1544-5111)로 연락 부탁 드려도 될까요?' or alertText == '발행일/인증번호를 확인하세요' or alertText == '핀번호/바코드를 확인하세요':
                crawling_value = 'book_and_life_book_pin_none'
                return crawling_value
            else:
                crawling_value = 'book_and_life_book_pin_use'
                return crawling_value

        # 북앤 라이프 모바일 도서 상품권 조회
        if input_data == 'book_and_life_mobile':
            pin1 = temp_array[1]
            pin2 = temp_array[2]
            pin3 = temp_array[3]
            pin4 = temp_array[4]
            pinAuth = temp_array[5]
            self.driver.find_element_by_id('radio3_gcct').click()  # 라디오 선택

            # 핀번호 입력
            self.driver.find_element_by_id('PIN1').send_keys(pin1)
            self.driver.find_element_by_id('PIN2').send_keys(pin2)
            self.driver.find_element_by_id('PIN3').send_keys(pin3)
            self.driver.find_element_by_id('PIN4').send_keys(pin4)

            # 인증번호 입력
            self.driver.find_element_by_id('pinAuthNum').send_keys(pinAuth)

            # 상품권 조회
            self.driver.find_element_by_id('useConfirmSelect').click()
            time.sleep(3)  # 조회 임의 대기시간

            ar = Alert(self.driver)
            alertText = ar.text
            print(alertText)
            ar.accept()
            # 미사용
            if alertText == '고객님, 상품권 번호가 잘못되었거나, 이미 사용된 것 같습니다. 계속 발생하면 고객센터(1544-5111)로 연락 부탁 드려도 될까요?' or alertText == '발행일/인증번호를 확인하세요' or alertText == '핀번호/바코드를 확인하세요':
                crawling_value = 'book_and_life_mobile_none'
                return crawling_value
            else:
                crawling_value = 'book_and_life_mobile_use'
                return crawling_value

        # 북앤 라이프 온라인 도서 상품권 조회
        if input_data == 'book_and_life_online':
            pin1 = temp_array[1]
            pin2 = temp_array[2]
            pin3 = temp_array[3]
            pin4 = temp_array[4]
            pinAuth = temp_array[5]
            self.driver.find_element_by_id('radio2_gcct').click()  # 라디오 선택

            # 핀번호 입력
            self.driver.find_element_by_id('PIN1').send_keys(pin1)
            self.driver.find_element_by_id('PIN2').send_keys(pin2)
            self.driver.find_element_by_id('PIN3').send_keys(pin3)
            self.driver.find_element_by_id('PIN4').send_keys(pin4)

            # 인증번호 입력
            self.driver.find_element_by_id('pinAuthNum').send_keys(pinAuth)

            # 상품권 조회
            self.driver.find_element_by_id('useConfirmSelect').click()
            time.sleep(3)  # 조회 임의 대기시간

            ar = Alert(self.driver)
            alertText = ar.text
            print(alertText)
            ar.accept()
            # 미사용
            if alertText == '고객님, 상품권 번호가 잘못되었거나, 이미 사용된 것 같습니다. 계속 발생하면 고객센터(1544-5111)로 연락 부탁 드려도 될까요?' or alertText == '발행일/인증번호를 확인하세요' or alertText == '핀번호/바코드를 확인하세요':
                crawling_value = 'book_and_life_online_none'
                return crawling_value
            else:
                crawling_value = 'book_and_life_online_use'
                return crawling_value
Example #31
0
def edit_campaign_click(target_name, **kwargs):
    """

    :rtype: object
    """
    target = target_name.lower()

    if target == 'send date input':
        location = locations.EditCampaign.Inputs.send_date
        helpers.click_or_type_date(location, **kwargs)
    elif target == 'requested return date input':
        location = locations.EditCampaign.Inputs.requested_return_date
        # Clear field if date is auto-generated; Maybe this should be in a helper?
        driver.find_element_by_xpath(location).clear()
        helpers.click_or_type_date(location, **kwargs)
    elif target == 'generate date input':
        location = locations.EditCampaign.Inputs.generate_date
        helpers.click_or_type_date(location, **kwargs)
    elif target == 'include most recent invalid input':
        location = locations.EditCampaign.Inputs.include_most_recent
        helpers.click_or_type(location, **kwargs)
    elif target == 'cover letter only input':
        location = locations.EditCampaign.Inputs.cover_letter_only
        helpers.click_or_type(location, **kwargs)
    elif target == 'include certexpress access input':
        location = locations.EditCampaign.Inputs.include_certexpress_access
        helpers.click_or_type(location, **kwargs)
    elif target == 'automatically send round input':
        location = locations.EditCampaign.Inputs.automatically_send_round
        helpers.click_or_type(location, **kwargs)
    elif target == 'notes input':
        location = locations.EditCampaign.Inputs.notes
        helpers.click_or_type(location, **kwargs)
    elif target == 'method select':
        location = locations.EditCampaign.Selects.method
        helpers.click_or_select(location, **kwargs)
    elif target == 'email template cover letter select':
        location = locations.EditCampaign.Selects.email_template_cover_letter
        helpers.click_or_select(location, **kwargs)
    elif target == 'overview link':
        helpers.click_helper(locations.EditCampaign.Links.overview)
    elif target == 'add round link':
        helpers.click_helper(locations.EditCampaign.Links.add_round)
    elif target == 'scheduling and delivery link':
        helpers.click_helper(
            locations.EditCampaign.Links.scheduling_and_delivery)
    elif target == 'select customers link':
        helpers.click_helper(locations.EditCampaign.Links.select_customers)
    elif target == 'preview link':
        helpers.click_helper(locations.EditCampaign.Links.preview)
    elif target == 'print link':
        helpers.click_helper(locations.EditCampaign.Links.print)
    elif target == 'send emails link':
        helpers.click_helper(locations.EditCampaign.Links.send_emails)
    elif target == 'clone round link':
        helpers.click_helper(locations.EditCampaign.Links.clone_round)
    elif target == 'delete round link':
        helpers.click_helper(locations.EditCampaign.Links.delete_round)
    elif target == 'customer number header link':
        helpers.click_helper(
            locations.EditCampaign.Links.customer_number_header)
    elif target == 'name header link':
        helpers.click_helper(locations.EditCampaign.Links.name_header)
    elif target[0:5] == 'round' and target[-4:] == 'link':
        if target[7] == ' ':
            number = target[6]  # Supports single digits
            helpers.click_helper(locations.EditCampaign.Links.round(number))
        elif target[8] == ' ':
            number = target[6:8]  # Supports double digits
            helpers.click_helper(locations.EditCampaign.Links.round(number))
        else:
            print(warn.SOME_PROBLEM)
    elif target == 'delete campaign button':
        helpers.click_helper(locations.EditCampaign.Buttons.delete_campaign)
    elif target == 'save campaign changes button':
        helpers.click_helper(
            locations.EditCampaign.Buttons.save_campaign_changes)
        time.sleep(2)
    elif target == 'send compliance document requests button':
        driver.find_element_by_xpath(
            locations.EditCampaign.Buttons.send_compliance_document_requests
        ).click()
        time.sleep(2)
        Alert(driver).accept()
    elif target == 'export overview data button':
        helpers.click_helper(
            locations.EditCampaign.Buttons.export_overview_data)
    elif target == 'first button':
        helpers.click_helper(locations.EditCampaign.Buttons.first)
    elif target == 'prev button':
        helpers.click_helper(locations.EditCampaign.Buttons.prev)
    elif target == 'page selector select':
        location = locations.EditCampaign.Selects.page_selector
        helpers.click_or_select(location, **kwargs)
    elif target == 'next button':
        helpers.click_helper(locations.EditCampaign.Buttons.next)
    elif target == 'last button':
        helpers.click_helper(locations.EditCampaign.Buttons.last)
    elif target == 'pdf - 1 merged file input':
        helpers.click_helper(locations.EditCampaign.Inputs.merged_file)
    elif target == 'zip - individual pdfs input':
        helpers.click_helper(locations.EditCampaign.Inputs.zip_individual)
    elif target == 'zip - merged pdf by page count input':
        helpers.click_helper(locations.EditCampaign.Inputs.zip_merged)
    elif target == 'create printable file button':
        helpers.click_helper(
            locations.EditCampaign.Buttons.create_printable_file)
    else:
        print(warn.INVALID_CLICK_TARGET)
Example #32
0
 def close_popup_alert(self):
     try:
         Alert(self.driver).accept()
     except:
         pass
driver = webdriver.Chrome("C:/Users/user/Desktop/chromedriver.exe")
driver.implicitly_wait(10)
driver.get('https://www.dsm-dms.com')

# login_btn click
driver.find_element_by_class_name('header--button').click()

# user_id, user_pw send
user_id, user_pw = driver.find_elements_by_class_name('modal--input')
user_id.send_keys('qwe5618')
user_pw.send_keys('zz142512')

driver.find_element_by_class_name('modal--submit').click()
driver.implicitly_wait(2)
time.sleep(2)
Alert(driver).accept()

# dms_reservation
driver.find_element_by_class_name('main--apply--card--link').click()

dms_room_list = driver.find_elements_by_class_name(
    'apply--content--menu--item')
time.sleep(2)
# driver.implicitly_wait(5)
dms_room_list[8].click()
WebDriverWait(driver, 3)
time.sleep(3)

# dms_11_reservation
dms_seat_list_11 = driver.find_elements_by_class_name(
    'apply--content--extension--seat')
Example #34
0
 def accept_alert(self):
     Alert(self.driver).accept()
     self.wait_success_alert()
Example #35
0
    def one_voter_votes(self, voter, direct=False):
        browser = self.browser

        if direct:
            url = voter["election_page_url"]
            browser.get(settings.SERVER_URL + "/vote.html#" + urlencode({"url": url}))

        else:
            # Bob has received 2 emails containing an invitation to vote and all necessary credentials (election page URL, username, password). He goes to the election page URL.
            browser.get(voter["election_page_url"])

            wait_a_bit()

            # He clicks on the "Start" button
            start_button_expected_label = "Start"
            start_button_css_selector = "#main button"
            start_button_element = wait_for_element_exists_and_contains_expected_text(browser, start_button_css_selector, start_button_expected_label, settings.EXPLICIT_WAIT_TIMEOUT)
            start_button_element.click()

        wait_a_bit()

        # A loading screen appears, then another screen appears. He clicks on the "Here" button
        here_button_expected_label = "here"
        here_button_css_selector = "#input_code button"
        here_button_element = wait_for_element_exists_and_contains_expected_text(browser, here_button_css_selector, here_button_expected_label, settings.EXPLICIT_WAIT_TIMEOUT)
        here_button_element.click()

        wait_a_bit()

        # A modal opens (it is an HTML modal created using Window.prompt()), with an input field. He types his credential.
        credential_prompt = Alert(browser)
        credential_prompt.send_keys(voter["credential"])
        credential_prompt.accept()

        wait_a_bit()

        # A new screen appears, which has a title "Step 2/6: Answer to questions", and a content:
        # "Question 1?"
        # "Question #1 of 1 — select between 1 and 2 answer(s)"
        # [ ] "Answer 1"
        # [ ] "Answer 2"
        # [Next]
        # (where "[ ]" is a checkbox, and [Next] is a button)

        # He fills his votes to each answer of the question
        answers_css_selector = "#question_div input[type=checkbox]"
        answers_elements = wait_for_elements_exist(browser, answers_css_selector, settings.EXPLICIT_WAIT_TIMEOUT) # or we could use find_element_by_xpath("//div[@id='question_div']/input[@type='checkbox'][2]")

        assert len(answers_elements) is 2
        question1_answer1_element = answers_elements[0]
        question1_answer2_element = answers_elements[1]
        voter_vote_to_question_1_answer_1 = voter["votes"]["question1"]["answer1"]
        voter_vote_to_question_1_answer_2 = voter["votes"]["question1"]["answer2"]
        voter_vote_to_question_1_answer_1_is_checked = question1_answer1_element.get_attribute('checked')
        voter_vote_to_question_1_answer_2_is_checked = question1_answer2_element.get_attribute('checked')
        assert voter_vote_to_question_1_answer_1_is_checked is None
        assert voter_vote_to_question_1_answer_2_is_checked is None
        if voter_vote_to_question_1_answer_1:
            question1_answer1_element.click()
        if voter_vote_to_question_1_answer_2:
            question1_answer2_element.click()

        wait_a_bit()

        # He clicks on the "Next" button
        next_button_expected_label = "Next"
        next_button_css_selector = "#question_div button"
        next_button_element = wait_for_element_exists_and_contains_expected_text(browser, next_button_css_selector, next_button_expected_label, settings.EXPLICIT_WAIT_TIMEOUT)
        next_button_element.click()

        wait_a_bit()

        """
        A new screen appears, showing:

        Step 3/6: Review and encrypt
        Question 1?
        - Answer 1

        Your ballot has been successfully encrypted, but has not been cast yet!

        Your smart ballot tracker is sLRilXoAYcodIrjWrOqPrVXLNlRyCJAqFeeHZ4WCajU

        We invite you to save it in order to check later that it is taken into account.

        [Continue]
        [Restart]
        """

        # He remembers the smart ballot tracker that is displayed.
        smart_ballot_tracker_css_selector = "#ballot_tracker"
        smart_ballot_tracker_element = wait_for_element_exists_and_has_non_empty_content(browser, smart_ballot_tracker_css_selector, settings.EXPLICIT_WAIT_TIMEOUT)
        smart_ballot_tracker_value = smart_ballot_tracker_element.get_attribute('innerText')
        assert len(smart_ballot_tracker_value) > 5

        voter["smart_ballot_tracker"] = smart_ballot_tracker_value

        # He clicks on the "Continue" button
        next_button_expected_label = "Continue"
        next_button_css_selector = "#div_submit input[type=submit][value='" + next_button_expected_label + "']"
        next_button_element = browser.find_element_by_css_selector(next_button_css_selector)
        next_button_element.click()

        wait_a_bit()

        # He types his voter username and password, and submits the form
        username_field_css_selector = "#main input[name=username]"
        username_field_element = wait_for_element_exists(browser, username_field_css_selector, settings.EXPLICIT_WAIT_TIMEOUT)
        username_field_element.send_keys(voter["username"])

        password_field_css_selector = "#main input[name=password]"
        password_field_element = browser.find_element_by_css_selector(password_field_css_selector)
        password_field_element.send_keys(voter["password"])

        wait_a_bit()

        password_field_element.submit()

        wait_a_bit()

        # He checks that the smart ballot tracker value that appears on screen is the same as the one he noted
        smart_ballot_tracker_verification_css_selector = "#ballot_tracker"
        smart_ballot_tracker_verification_element = wait_for_element_exists_and_has_non_empty_content(browser, smart_ballot_tracker_verification_css_selector, settings.EXPLICIT_WAIT_TIMEOUT)
        smart_ballot_tracker_verification_value = smart_ballot_tracker_verification_element.get_attribute('innerText')
        assert len(smart_ballot_tracker_verification_value) > 5

        assert smart_ballot_tracker_verification_value == voter["smart_ballot_tracker"]

        # He clicks on the "I cast my vote" button
        submit_button_css_selector = "#main input[type=submit]"
        submit_button_element = browser.find_element_by_css_selector(submit_button_css_selector)
        submit_button_element.click()
Example #36
0
 def switch_to_alert(self):
     """Switches focus to an alert on the page.
     Usage:
         driver.switch_to_alert()
     """
     return Alert(self)
Example #37
0
 def handle_alert(self):
     alert = Alert(self.driver)
     alert.accept()
Example #38
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import random
from korean_name_generator import namer
import string
import time
from selenium.webdriver.common.alert import Alert

driver = webdriver.Chrome(
    "/Users/goyoonjae/Desktop/insta_follower/chromedriver")
url = 'http://www.instagram.com'
driver.get(url)

da = Alert(driver)

driver.implicitly_wait(5)
driver.find_element_by_css_selector(
    '#react-root > section > main > article > div.rgFsT > div:nth-child(2) > div > p > a > span'
).click()  # 회원가입버튼


def mail_open():
    driver.execute_script('window.open("https://www.ruu.kr")')
    print("ruu.kr 접속 성공!")
    # ==========================================
    driver.switch_to.window(driver.window_handles[1])
    driver.implicitly_wait(5)
    driver.find_element_by_css_selector('#id').click()
    driver.find_element_by_css_selector('#id').send_keys(userid)
    time.sleep(15)
Example #39
0
def handle_alert(driver):
    alert = Alert(driver)
    alert.accept()
Example #40
0
# 等待alert窗口显示后存储到变量中
alert = wait.until(expected_conditions.alert_is_present())
# 将警告中的文本存储到变量
alert_text = alert.text
# 模拟点击确定按钮
alert.accept()

# js的confirm确认框
browser.find_element_by_link_text("xxx").click()
wait.until(expected_conditions.alert_is_present())
alert = browser.switch_to.alert
alert_text = alert.text
alert.dismiss()

# js的prompt提示框
alert = Alert(browser)
alert.send_keys("xxx")
alert.accept()

# http代理设置
Proxy = "host:port"
webdriver.DesiredCapabilities.CHROME["proxy"] = {
    "httpProxy": Proxy,
    "ftpProxy": Proxy,
    "sslProxy": Proxy,
    "proxyType": "MANUAL",
}

with webdriver.Chrome() as driver:
    driver.get("xxx.com")
Example #41
0
            print("=" * size)
            print('해당 주차 강의를 다운로드 합니다. 완료될 때까지 기다려주세요.')
            print('- 온라인 출석부에서 해당 동영상 강의 열람 횟수가 1회 증가합니다.')
            vod_list = week.find_all('li',
                                     {'class': 'activity vod modtype_vod'})
            for i in range(0, len(vod_list)):
                vodLink = re.search(r'https://.*\d*', str(vod_list[i])).group()
                vodLink = vodLink[:vodLink.find('"')]
                vodLink = vodLink.replace('view', 'viewer')
                if (vodLink.find(
                        'https://plato.pusan.ac.kr/mod/vod/viewer.php?') == -1
                    ):
                    continue
                driver.get(vodLink)
                try:
                    da = Alert(driver)
                    da.dismiss()
                except:
                    print("", end='')
                html = driver.page_source
                soup = BS4(html, 'html.parser')
                source = str(soup.find_all('source'))
                source = source[source.find('https'):source.find('m3u8') + 4]
                fileDownload(
                    courseName + week.attrs['aria-label'] + '_' + str(i + 1),
                    source)

    driver.get('https://plato.pusan.ac.kr/')
    driver.find_element_by_xpath(
        '//*[@id="page-header"]/div[1]/div[2]/ul/li[2]/a').click()
    driver.quit()
Example #42
0
 def click_alert_dismiss(self):
     '''点击弹出框的取消'''
     Alert(self.driver).dismiss()
from selenium.webdriver import Firefox
from selenium.webdriver.common.alert import Alert

browser = Firefox()

browser.get('http://selenium.dunossauro.live/aula_11_a')

browser.find_element_by_id('prompt').click()

alerta = Alert(browser)

alerta.accept()
alerta.dismiss()
Example #44
0
 def get_alert_text(self):
     '''点击弹出框的取消'''
     return Alert(self.driver).text
Example #45
0
    def test_pruebas_ini_sesion(self):
        driver = self.driver
        driver.get(self.base_url + "/#/VLogin")
        actions = ActionChains(self.driver)
        alert = Alert(self.driver)
        
        driver.find_element_by_id("fLogin_usuario").clear()
        driver.find_element_by_id("fLogin_usuario").send_keys("Usuario")
        time.sleep(.5)
        driver.find_element_by_id("fLogin_clave").clear()
        driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa")
        time.sleep(.5)
        driver.find_element_by_xpath("//button[@id='conectate']").click()
        time.sleep(2)
        
######################## Ayuda y Foro sin titulo #############################################   
      
        driver.find_element_by_xpath("//a[@ng-click='VForos()']").click()
        time.sleep(2)
        driver.find_element_by_xpath("//a[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        '''
        driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click()
        time.sleep(.5)
        driver.find_element_by_xpath("//a[@ng-click='__ayuda()']").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        '''
######################## Creacion de Foro #############################################         
        
        driver.find_element_by_id("fForo_texto").send_keys("Foro Prueba")
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        
######################## Prueba Foro con mismo nombre #############################################         
        '''
        driver.find_element_by_xpath("//button[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_id("fForo_texto").send_keys("Nuevo ForoR")
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        actions.key_down(Keys.CONTROL)
        actions.send_keys('r')
        actions.key_up(Keys.CONTROL)
        actions.perform()
        time.sleep(.5)
        '''
######################## Hilo sin titulo ni contenido y ayuda ############################################# 
        
        driver.find_element_by_link_text("Foro Prueba").click()
        '''
        driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click()
        time.sleep(1)
        driver.find_element_by_xpath("//a[@ng-click='__ayuda()']").click()
        time.sleep(1)
        '''
        actions.key_down(Keys.CONTROL)
        actions.send_keys('r')
        actions.key_up(Keys.CONTROL)
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("//a[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        '''
        driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click()
        time.sleep(1)
        driver.find_element_by_xpath("//a[@ng-click='__ayuda()']").click()
        time.sleep(1)
        
        actions.key_down(Keys.CONTROL)
        actions.send_keys('r')
        actions.key_up(Keys.CONTROL)
        actions.perform()
        time.sleep(.5)
        '''
######################## Hilo sin titulo ############################################# 
        
        driver.find_element_by_xpath("//a[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_id("fHilo_contenido").clear()
        driver.find_element_by_id("fHilo_contenido").send_keys("Nuevo Contenido")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)

######################## Hilo sin contenido ############################################# 
        
        driver.find_element_by_xpath("//a[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_id("fHilo_titulo").clear()
        driver.find_element_by_id("fHilo_titulo").send_keys("Nuevo Hilo")
        driver.find_element_by_id("fHilo_contenido").clear()
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)


######################## Creacion Hilo ############################################# 
        
        driver.find_element_by_xpath("//a[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_id("fHilo_titulo").clear()
        driver.find_element_by_id("fHilo_titulo").send_keys("Nuevo Hilo")
        driver.find_element_by_id("fHilo_contenido").clear()
        driver.find_element_by_id("fHilo_contenido").send_keys("Nuevo Contenido")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        

######################## Creacion Hilo Existente ############################################# 
        '''
        driver.find_element_by_xpath("//a[@id='config']").click()
        time.sleep(.5)
        driver.find_element_by_id("fHilo_titulo").clear()
        driver.find_element_by_id("fHilo_titulo").send_keys("Nuevo Hilo")
        driver.find_element_by_id("fHilo_contenido").clear()
        driver.find_element_by_id("fHilo_contenido").send_keys("Nuevo Contenido")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        '''
######################## Publicacion sin contenido y ayuda ############################################# 
        
        driver.find_element_by_link_text("Nuevo Hilo").click() 
        time.sleep(1)
        
        actions.key_down(Keys.CONTROL)
        actions.send_keys('r')
        actions.key_up(Keys.CONTROL)
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("//button[@id='btnForos']").click()
        
        #driver.find_element_by_xpath("//span[@class='glyphicon glyphicon-info-sign']").click() ###### AYUDA #######################################
        time.sleep(1)
        

        
######################## Publicacion sin titulo ############################################# 
        
        driver.find_element_by_id("fpublicacion_titulo").clear()
        driver.find_element_by_id("fpublicacion_titulo").send_keys("")
        driver.find_element_by_id("fpublicacion_texto").clear()
        driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Contenido")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        
######################## Publicacion Vacia ############################################# 
        
        driver.find_element_by_id("fpublicacion_titulo").clear()
        driver.find_element_by_id("fpublicacion_titulo").send_keys("")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
######################## Crear Publicacion ############################################# 
        
        driver.find_element_by_id("fpublicacion_texto").clear()
        driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Texto")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        
######################## Publicacion nuevo titulo ############################################# 
        
        driver.find_element_by_id("fpublicacion_titulo").clear()
        driver.find_element_by_id("fpublicacion_titulo").send_keys("Nueva Titulo")
        driver.find_element_by_id("fpublicacion_texto").clear()
        driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Comentario")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        
######################## Publicacion "duplicada" ############################################# 
        
        driver.find_element_by_id("fpublicacion_titulo").clear()
        driver.find_element_by_id("fpublicacion_titulo").send_keys("Nueva Titulo")
        driver.find_element_by_id("fpublicacion_texto").clear()
        driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Comentario")
        time.sleep(1)
        driver.find_element_by_xpath("//button[@type='submit']").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        
######################## Publicaciones Anidadas ############################################# 
        
        driver.find_element_by_xpath("(//a[@ng-click='responderPublicacion(publicacion)'])[2]").click()
        
        driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").clear()
        driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").send_keys("Nuevo Comentario 2")
        time.sleep(1)
        driver.find_element_by_xpath("(//button[@type='submit'])[2]").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
                
        driver.find_element_by_xpath("(//a[@ng-click='responderPublicacion(publicacion)'])[3]").click()
        
        driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").clear()
        driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").send_keys("Nuevo Comentario 3")
        time.sleep(1)
        driver.find_element_by_xpath("(//button[@type='submit'])[2]").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("(//a[@ng-click='responderPublicacion(publicacion)'])[2]").click()
        
        driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").clear()
        driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").send_keys("Nuevo Comentario 2.2")
        time.sleep(1)
        driver.find_element_by_xpath("(//button[@type='submit'])[2]").click()
        time.sleep(1)
        
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
######################## Eliminar Publicaciones ############################################# 
        
        driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[3]").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)   
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[2]").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[6]").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[5]").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)       
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
        driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[4]").click()
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()
        time.sleep(.5)
        
######################## Eliminar Hilos ############################################# 
        actions.send_keys(Keys.ALT)
        actions.send_keys(Keys.ARROW_LEFT)
        actions.perform()
        
        driver.find_element_by_xpath("(//a[contains(@ng-click,'AElimHilo1')])[1]").click() 
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        
        actions.send_keys(Keys.ALT)
        actions.send_keys(Keys.ARROW_LEFT)
        actions.perform()
        
######################## Eliminar Foro #############################################         
        
        
        driver.find_element_by_xpath("(//a[contains(@ng-click,'AElimForo1')])[last()]").click() 
        time.sleep(0.5)
        alert.accept()
        time.sleep(.5)
        actions.send_keys(Keys.CONTROL)
        actions.send_keys('r')
        actions.perform()