コード例 #1
0
ファイル: test_04_settings.py プロジェクト: SamR1/rdltr
def test_settings_display_tags(selenium: WebDriver) -> None:
    register_valid_user(selenium)
    selenium.get(f'{URL}settings')

    box = selenium.find_element_by_class_name('rdltr-box')
    box.find_elements_by_tag_name('button')[1].click()

    container = selenium.find_element_by_class_name('container')
    rows = container.find_elements_by_class_name('row')

    buttons = rows[0].find_elements_by_tag_name('button')
    back_to_settings = buttons[0]
    assert 'Back to settings' in back_to_settings.text
    assert 'Add a tag' in buttons[1].text

    rows[1].find_elements_by_tag_name('input')
    assert 'Search' in rows[1].find_element_by_tag_name('span').text

    table = rows[2].find_element_by_tag_name('table')
    thead_th = table.find_element_by_tag_name(
        'thead').find_elements_by_tag_name('th')
    assert 'Id' in thead_th[0].text
    assert 'Name' in thead_th[1].text
    assert 'Nb articles' in thead_th[2].text
    assert 'Action' in thead_th[3].text
    tbody_td = table.find_element_by_tag_name(
        'tbody').find_elements_by_tag_name('td')
    assert tbody_td == []
コード例 #2
0
def is_login(driver: WebDriver) -> bool:
    driver.get(MYPAGE_URL)
    try:
        driver.find_element_by_class_name('log_in_id')
        return True
    except NoSuchElementException:
        return False
コード例 #3
0
    def verificar_elemento_html_por_class_name(class_name: str,
                                               web_driver: WebDriver):

        try:
            web_driver.find_element_by_class_name(class_name)
            return True
        except NoSuchElementException:
            return False
コード例 #4
0
ファイル: whatslog.py プロジェクト: lzfelix/whatslogger
def find_contact(driver: WebDriver, contact: str) -> None:
    search_box = driver.find_element_by_class_name(CONTACT_SEARCH_BOX_CLASS)
    search_box.send_keys(contact)
    driver.implicitly_wait(2)

    # Click on contact card on the left pane
    driver.find_element_by_class_name(CONTACT_MATCHED_SEARCH_CLASS).click()
    driver.implicitly_wait(10)
コード例 #5
0
    def verificar_elemento_html_hasta_no_existir_en_el_dom_html(
            web_driver: WebDriver,
            time=5,
            id=None,
            xpath=None,
            link_text=None,
            partial_link_text=None,
            name=None,
            tag_name=None,
            class_name=None,
            css_selector=None):

        msg_selector_html_a_localizar = HtmlActions.generar_identificador_excepcion(
            id, xpath, link_text, partial_link_text, name, tag_name,
            class_name, css_selector)

        tiempo_inicial = Temporizador.obtener_tiempo_timer()

        while True:
            try:
                if id is not None:
                    web_driver.find_element_by_id(id)
                elif xpath is not None:
                    web_driver.find_element_by_xpath(xpath)
                elif link_text is not None:
                    web_driver.find_element_by_link_text(link_text)
                elif partial_link_text is not None:
                    web_driver.find_element_by_partial_link_text(
                        partial_link_text)
                elif name is not None:
                    web_driver.find_element_by_name(name)
                elif tag_name is not None:
                    web_driver.find_element_by_tag_name(tag_name)
                elif class_name is not None:
                    web_driver.find_element_by_class_name(class_name)
                elif css_selector is not None:
                    web_driver.find_element_by_css_selector(css_selector)

                segundos_transcurridos = Temporizador.obtener_tiempo_timer(
                ) - tiempo_inicial

                if segundos_transcurridos > time:
                    e = TimeoutException()
                    e.msg = webdriver_actions_constantes.WEBDRIVER_WAIT_UNTIL_NOT_TIMEOUT_EXCEPTION.format(
                        time, msg_selector_html_a_localizar, e.msg)

                    raise e
                else:
                    pass

            except NoSuchElementException:
                break
コード例 #6
0
    def login_click_bt(driver: WebDriver, username: str, password: str):
        if "You’re now logged in to BT Wi-fi" in driver.page_source:
            logger.warning("Already logged... weird, doing nothing")
            return True

        # this is the weird bug 'wifi access has expired'
        if len(driver.find_elements_by_link_text("Buy more time")) > 0:
            driver.find_element_by_link_text("Logout").click()
            # TODO how to wait?

        driver.find_element_by_id("username").send_keys(username)
        driver.find_element_by_id("password-password").send_keys(password)
        driver.find_element_by_class_name("lgnbtn").click()
        return True
コード例 #7
0
def save_article_in_db(driver: WebDriver, article_title: str):
    """
    Creates new article in database from data retrieved from the web page.
    :param driver: WebDriver
    :param article_title: str
    :return:
    """
    article_content = driver.find_element_by_class_name("post-content").text
    article_author = driver.find_element_by_class_name("author-name").text
    new_article = Article(article_author=article_author,
                          article_title=article_title,
                          article_content=article_content)
    db.add(new_article)
    db.commit()
コード例 #8
0
def login(
    driver: WebDriver,
    username: str,
    password: SecretStr,
    timeout: int = 5
) -> bool:
    if is_login(driver):
        return True
    else:
        WebDriverWait(driver, timeout)
        driver.find_element_by_name('login_id').send_keys(username)
        driver.find_element_by_name('login_pass').send_keys(password)
        driver.find_element_by_class_name('submit_b') \
              .find_element_by_tag_name('input').click()
        return is_login(driver)
コード例 #9
0
def find_and_select_random_radio_and_click_next(driver: WebDriver):
    parent_div_radio_element = driver.find_element_by_class_name("m-b-xs")
    time.sleep(2)
    child_radio_div_elements = parent_div_radio_element.find_elements_by_xpath("//input[@type='radio']");
    RADIO_SELECTORS_DICT = {}
    for index in range(len(child_radio_div_elements)):
        child_radio_element = child_radio_div_elements[index]
        key_name = "radio" + str(index)
        radio_element_xpath = f"//input[@id='" + str(child_radio_element.get_attribute("id")) + "']"
        key_value = Selector(By.XPATH, radio_element_xpath, type=ElementType.RADIO)

        if index == 0:
            rsdict = {}
            rsdict[key_name] = key_value
            RADIO_SELECTORS_DICT["product radio info"] = rsdict
        else:
            rsdict = RADIO_SELECTORS_DICT["product radio info"]
            rsdict[key_name] = key_value
            RADIO_SELECTORS_DICT.clear()
            RADIO_SELECTORS_DICT["product radio info"] = rsdict

    radio_selectors = RADIO_SELECTORS_DICT["product radio info"]
    check_random_radio(driver, radio_selectors)

    nextbtnclick(driver)
コード例 #10
0
    def scrape_product(driver: WebDriver) -> Dict:
        """Scrape a product page.

        :param driver: selenium web driver
        """

        price = None
        deal_price = None
        rrp = None

        product_title = driver.find_element_by_id("productTitle").text
        availability = driver.find_element_by_id("availability").text

        try:
            price = driver.find_element_by_id("priceblock_ourprice").text
        except NoSuchElementException:
            deal_price = driver.find_element_by_id("priceblock_dealprice").text
            rrp = driver.find_element_by_class_name(
                "priceBlockStrikePriceString").text

        return {
            "Product Name": product_title,
            "Product Price": price,
            "Product Deal": deal_price,
            "Product RRP": rrp,
            "Product Availability": availability,
            "Date": datetime.datetime.now(),
        }
コード例 #11
0
def find_progress_bar(driver: WebDriver, element_name: str):
    # search for parent progress bar div class
    parent_div_element = driver.find_element_by_class_name(
        "learn__category-progress-container")
    #child_radio_div_elements = parent_div_radio_element.find_elements_by_tag_name("div")
    p_tag = parent_div_element.find_element_by_tag_name("p")
    logging.debug(p_tag.text)
コード例 #12
0
def login():
    global driver
    global wait
    print('Money lover: Starting selenium session')
    driver = WebDriver(
        command_executor='http://localhost:4444/wd/hub',
        desired_capabilities={'browserName': 'firefox'})
    wait = WebDriverWait(driver, 10)
    print('Money lover: Starting login process')
    driver.get(URL)
    wait.until(lambda d: d.find_element_by_id('input-26'))
    driver.find_element_by_id('input-26').send_keys(ML_USER)
    driver.find_element_by_id('input-28').send_keys(ML_PASS)
    driver.find_element_by_class_name('btn-submit-ml').click()
    time.sleep(10)
    print('Money lover: login process finished')
    wait.until(lambda d: d.find_element_by_id('master-container'))
コード例 #13
0
def watch_current_video(driver: WebDriver, max_time: int = 420) -> None:
    """Watches the YouTube video on the currently selected page.
    Arguments:
    driver - The webdriver, it has to be navigated to a YouTube video before calling this function.
    with_progress - If true, periodically print the watch progress.
    max_time - Maximum time spent watching this video before aborting.
    """

    # Wait for YouTube to finish loading the player
    player_div = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable(
            (By.CSS_SELECTOR, "div#player.ytd-watch-flexy")))
    start_time = time.time()
    logging.info("Started watching")
    current_time_elem = driver.find_element_by_css_selector(
        "span.ytp-time-current")
    duration_time_elem = driver.find_element_by_css_selector(
        "span.ytp-time-duration")

    # The watch next video button gets created later I guess ¯\_(ツ)_/¯
    up_next_button_elem = None

    # We wiggle the virtual mouse to prevent YouTube from hiding the player controls,
    # because we read the watched time from there
    move_to_player = webdriver.ActionChains(driver)
    move_to_player.move_to_element_with_offset(player_div, 100, 100)
    wiggle_mouse = webdriver.ActionChains(driver)
    wiggle_mouse.move_by_offset(10, 0)
    wiggle_mouse.pause(1)
    wiggle_mouse.move_by_offset(-10, 0)
    move_to_player.perform()
    while True:
        # The buttom time bar won't update if it is not visible so move the mouse to show it
        wiggle_mouse.perform()
        logging.info(
            f'{current_time_elem.get_attribute("textContent")} of {duration_time_elem.get_attribute("textContent")}'
        )

        # Resting is important
        time.sleep(5)

        # If the 'Up next' screen is showing, we are done watching this video
        try:
            if up_next_button_elem:
                if up_next_button_elem.is_displayed():
                    break
            else:
                up_next_button_elem = driver.find_element_by_class_name(
                    "ytp-autonav-endscreen-upnext-button")
        except:
            # The next button is created lazily, so sometimes its missing
            logging.warning("No next button found while watching video")

        if time.time() - start_time >= max_time:
            break

    logging.info("finished watching video")
コード例 #14
0
def enter_link(driver: WebDriver, link: str):
    input_box_id = "link"
    input_box: WebElement = driver.find_element_by_id(input_box_id)
    hover(driver, input_box)
    input_box.send_keys(link)
    
    download_btn_class = "btn-primary"
    download_btn: WebElement = driver.find_element_by_class_name(download_btn_class)
    hover(driver, download_btn)
    download_btn.click()
コード例 #15
0
ファイル: test_04_settings.py プロジェクト: SamR1/rdltr
def test_settings_display_categories(selenium: WebDriver) -> None:
    register_valid_user(selenium)
    menus = selenium.find_elements_by_class_name('menu')
    menus[1].click()

    box = selenium.find_element_by_class_name('rdltr-box')
    buttons = box.find_elements_by_tag_name('button')
    assert 'Categories' in buttons[0].text
    assert 'Tags' in buttons[1].text
    assert 'Back to home' in buttons[2].text

    buttons[0].click()

    container = selenium.find_element_by_class_name('container')
    rows = container.find_elements_by_class_name('row')

    buttons = rows[0].find_elements_by_tag_name('button')
    back_to_settings = buttons[0]
    assert 'Back to settings' in back_to_settings.text
    assert 'Add a category' in buttons[1].text

    rows[1].find_elements_by_tag_name('input')
    assert 'Search' in rows[1].find_element_by_tag_name('span').text

    # default category should exist. this category can not be deleted
    table = rows[2].find_element_by_tag_name('table')
    thead_th = table.find_element_by_tag_name(
        'thead').find_elements_by_tag_name('th')
    assert 'Id' in thead_th[0].text
    assert 'Name' in thead_th[1].text
    assert 'Description' in thead_th[2].text
    assert 'Nb articles' in thead_th[3].text
    assert 'Action' in thead_th[4].text
    tbody_td = table.find_element_by_tag_name(
        'tbody').find_elements_by_tag_name('td')
    assert 'default' in tbody_td[1].text
    assert (len(
        tbody_td[1].find_elements_by_class_name('badge-rdltr-small')) == 1)
    assert 'Default category' in tbody_td[2].text
    assert '0' in tbody_td[3].text
    assert len(tbody_td[4].find_elements_by_class_name('fa-trash')) == 0
コード例 #16
0
def test_login_not_existing_user(selenium: WebDriver) -> None:
    user_name = random_string()
    user_infos = {
        'username': user_name,
        'email': f'{user_name}@example.com',
        'password': '******',
        'password_conf': 'p@ssw0rd',
    }

    login(selenium, user_infos, True)
    nav = selenium.find_element_by_tag_name('nav')
    nav_text = nav.text
    assert 'Register' in nav_text
    assert 'Log in' in nav_text
    errors = selenium.find_element_by_class_name('alert-danger').text
    assert 'Invalid credentials.' in errors
コード例 #17
0
ファイル: GetDailyWord.py プロジェクト: VicoandMe/Daily_Word
def GetDailyWord():
    capabilities = {"loggingPrefs": {}, "xwalkOptions": {"binary": "/usr/bin/xwalk", "debugPort": "12450"}}
    driver = WebDriver("http://127.0.0.1:9515", desired_capabilities=capabilities, keep_alive=True)

    driver.get("http://cn.bing.com/dict/")

    word = driver.find_element_by_class_name("client_daily_word_en")
    word_text = word.text

    pronounce = driver.find_elements_by_class_name("client_daily_word_pn_pn")
    pronounce_text = []
    pronounce_text.append(pronounce[0].text)
    pronounce_text.append(pronounce[1].text)

    WriteWordList(word_text + " " + pronounce[0].text + " " + pronounce[1].text)
    audio = driver.find_elements_by_class_name("client_aud_o")
    audio1_onmouseover = audio[0].get_attribute("onmouseover")
    audio1_onclick = audio[0].get_attribute("onclick")
    DownLoad_mp3(audio[0].get_attribute("onclick").split("'")[1], word_text + "_US")

    audio2_onmouseover = audio[1].get_attribute("onmouseover")
    audio2_onclick = audio[1].get_attribute("onclick")
    DownLoad_mp3(audio[1].get_attribute("onclick").split("'")[1], word_text + "_UK")

    translate = driver.find_element_by_class_name("client_daily_word_zh")
    translate_text = translate.text

    picture1_src = driver.find_element_by_id("emb1").get_attribute("src")
    picture2_src = driver.find_element_by_id("emb2").get_attribute("src")
    picture3_src = driver.find_element_by_id("emb3").get_attribute("src")
    DownLoad_jpg(picture1_src, word_text + "1")
    DownLoad_jpg(picture2_src, word_text + "2")
    DownLoad_jpg(picture3_src, word_text + "3")

    html_src = (
        '<head>\
<meta content="text/html; charset=utf-8" http-equiv="content-type" />\
<title>Daily word</title>\
<link rel="stylesheet" type="text/css" href="daily-word/daily.css"></link>\
</head>\
<body>\
<div class="client_daily_word_content">\
<div class="client_daily_words_bar">\
  <div class="client_daily_word_en">\
    <a id="word" href="http://bing.com.cn/dict/search?q='
        + word_text
        + '"h="ID=Dictionary,5014.1">'
        + word_text
        + '</a>\
  </div>\
  <div class="client_daily_word_pn">\
    <div class="client_daily_word_pn_pn" lang="en">'
        + pronounce_text[0]
        + '</div>\
    <div class="client_daily_word_pn_audio">\
      <div class="client_icon_container">\
	<audio id="us_pronun" src=./daily-word/mp3/'
        + word_text
        + "_US.mp3"
        + ' controls="contrils"></audio>\
	</a>\
      </div>\
    </div>\
  </div>\
  <div class="client_daily_word_pn">\
    <div class="client_daily_word_pn_pn" lang="en">'
        + pronounce_text[1]
        + '</div>\
    <div class="client_daily_word_pn_audio">\
      <div class="client_icon_container">\
	<audio id="us_pronun" src=./daily-word/mp3/'
        + word_text
        + "_UK.mp3"
        + ' controls="contrils"></audio>\
	</a>\
      </div>\
    </div>\
  </div>\
  <div class="client_daily_word_zh">'
        + translate_text
        + '</div>\
</div>\
<div class="client_daily_pic_bar">\
  <a href="http://bing.com.cn/dict/search?q='
        + word_text
        + '"class="client_daily_pic_item" target="_blank" h="ID=Dictionary,5017.1">\
    <img class="rms_img" height="80" id="emb1" src="'
        + "./daily-word/picture/"
        + word_text
        + "1"
        + ".jpg"
        + '" width = "80" />\
  </a>\
  <a href="http://bing.com.cn/dict/search?q='
        + word_text
        + '"class="client_daily_pic_item" target="_blank" h="ID=Dictionary,5017.1">\
    <img class="rms_img" height="80" id="emb2" src="'
        + "./daily-word/picture/"
        + word_text
        + "2"
        + ".jpg"
        + '" width = "80" />\
  </a>\
  <a href="http://bing.com.cn/dict/search?q='
        + word_text
        + '"class="client_daily_pic_item" target="_blank" h="ID=Dictionary,5017.1">\
    <img class="rms_img" height="80" id="emb3" src="'
        + "./daily-word/picture/"
        + word_text
        + "3"
        + ".jpg"
        + '" width = "80" />\
  </a>\
</div>\
</div>\
</div>\
<script src="daily-word/daily.js"></script>\
</body>\
<html>\
'
    )
    with open(word_text + ".html", "w+") as fp:
        html_src = html_src.encode("utf-8")
        fp.write(html_src)
コード例 #18
0
def try_open_filters(driver: WebDriver):
    if not driver.find_element_by_class_name("lite-filter-bar").is_displayed():
        driver.find_element_by_id("show-filters-link").click()
        # Delay is necessary as driver can fail to click filters
        time.sleep(0.5)
コード例 #19
0
    def run(driver: WebDriver):
        nonlocal no
        if not no:
            elem = driver.find_element(By.XPATH, "//a[text()='投票']")
            if not elem:
                elem = driver.find_element(By.XPATH, "//a[text()='今日已投票']")
                if elem:
                    driver.delete_all_cookies()
                    driver.refresh()
                return None

            elem.click()
            elem_container = driver.find_element_by_class_name(
                "modal__container")
            if elem_container.is_displayed():
                no += 1
                return elem_container
        elif no == 1:
            elem_vote_options = driver.find_elements(
                By.XPATH, "//div/div/label[@class='label']")
            if not elem_vote_options:
                return None

            for elem in elem_vote_options:
                if not elem.is_displayed():
                    break
                elem.click()
                for_input = driver.find_element_by_id(
                    elem.get_attribute("for"))
                if not for_input.is_selected():
                    break
            else:
                no += 1
                return elem_vote_options
        if no == 2:

            driver.add_cookie({
                "name": "uuid",
                "value": generate_uuid(),
                "domain": ".businessweekly.com.tw",
                "size": 40,
            })
            elem = None
            try:
                elem = driver.find_element(By.XPATH, r"//a[text()='確認送出']")
                if elem and elem.is_enabled():
                    elem.click()
            except Exception as e:
                if driver.find_element_by_id("gdrp-el"):
                    driver.execute_script(
                        """document.getElementById("gdrp-el").remove();""")
            finally:
                elem_container = driver.find_element_by_class_name(
                    "modal__container")
                if elem_container and elem_container.find_element(
                        By.XPATH, "//img[@alt='投票完成']"):
                    no += 1
                    return True
                if "投票完成" in driver.page_source:
                    no += 1
                    return True

        return None
コード例 #20
0
    def borrar_archivo_claro_drive(webdriver_test_ux: WebDriver, json_eval,
                                   nombre_archivo_sin_ext: str,
                                   ext_archivo: str):

        nombre_completo_de_la_imagen = '{}{}'.format(nombre_archivo_sin_ext,
                                                     ext_archivo)
        tiempo_step_inicio = None
        fecha_inicio = Temporizador.obtener_fecha_tiempo_actual()

        # verifica que se haya iniciado sesion correctamente
        if not UtilsEvaluaciones.se_ingreso_correctamente_a_la_sesion(
                json_eval):
            json_eval = UtilsEvaluaciones.generar_json_inicio_de_sesion_incorrecta(
                json_eval, tiempo_step_inicio, fecha_inicio, 4,
                const_claro_drive.
                MSG_OUTPUT_BORRADO_ARCHIVO_MSG_ERROR_INICIO_SESION)

            return json_eval

        # verifica que se haya iniciado sesion correctamente
        if not UtilsEvaluaciones.se_cargo_correctamente_el_fichero(json_eval):
            json_eval = UtilsEvaluaciones.generar_json_inicio_de_sesion_incorrecta(
                json_eval, tiempo_step_inicio, fecha_inicio, 4,
                const_claro_drive.
                MSG_OUTPUT_BORRADO_ARCHIVO_MSG_ERROR_CARGA_ARCHIVO)

            return json_eval

        try:
            action = ActionChains(webdriver_test_ux)

            HtmlActions.verificar_display_flex_modal_mensaje_de_exito(
                webdriver_test_ux)

            UtilsEvaluaciones.esperar_aparicion_modal_de_exito(
                webdriver_test_ux)
            UtilsEvaluaciones.esperar_desaparicion_modal_exito(
                webdriver_test_ux)

            archivo_localizado_por_descargar = HtmlActions.webdriver_wait_element_to_be_clickable(
                webdriver_test_ux,
                20,
                xpath=const_claro_drive.
                BORRAR_ARCHIVO_XPATH_ARCHIVO_POR_DESCARGAR.format(
                    nombre_archivo_sin_ext))

            action.move_to_element(archivo_localizado_por_descargar)

            action.perform()

            lista_de_divs_de_archivos = webdriver_test_ux.find_elements_by_class_name(
                const_claro_drive.BORRAR_ARCHIVO_CLASS_NAME_FILENAME)

            if len(lista_de_divs_de_archivos) != 0:
                for div in lista_de_divs_de_archivos:

                    nombre_archivo_sin_extension_obtenido = div.find_element_by_class_name(
                        const_claro_drive.
                        BORRAR_ARCHIVO_CLASS_NAME_NAME_WITHOUT_EXT
                    ).get_attribute(
                        const_claro_drive.BORRAR_ARCHIVO_ATTR_INNER_TEXT)

                    nombre_archivo_sin_extension_obtenido = nombre_archivo_sin_extension_obtenido.strip(
                    )

                    extension_del_archivo_obtenido = webdriver_test_ux.find_element_by_class_name(
                        const_claro_drive.BORRAR_ARCHIVO_EXT).get_attribute(
                            const_claro_drive.BORRAR_ARCHIVO_ATTR_INNER_TEXT)

                    extension_del_archivo_obtenido = extension_del_archivo_obtenido.strip(
                    )

                    nombre_archivo_formateado = '{}{}'.format(
                        nombre_archivo_sin_extension_obtenido,
                        extension_del_archivo_obtenido)

                    if nombre_archivo_formateado == nombre_completo_de_la_imagen:

                        lista_botones = div.find_elements_by_class_name(
                            const_claro_drive.BORRAR_ARCHIVO_CLASS_NAME_ACTION)

                        HtmlActions.verificar_display_flex_modal_mensaje_de_exito(
                            webdriver_test_ux)

                        if len(lista_botones) > 0:

                            boton_borrar_archivo = lista_botones[-7]

                            HtmlActions.verificar_display_flex_modal_mensaje_de_exito(
                                webdriver_test_ux)

                            tiempo_step_inicio = Temporizador.obtener_tiempo_timer(
                            )

                            HtmlActions.click_en_elemento_html_con_intentos(
                                boton_borrar_archivo,
                                5,
                                class_name=const_claro_drive.
                                BORRAR_ARCHIVO_CLASS_NAME_ACTION)

                            # HtmlActions.click_html_element(
                            #     boton_borrar_archivo, class_name=const_claro_drive.BORRAR_ARCHIVO_CLASS_NAME_ACTION)

                            HtmlActions.verificar_display_flex_modal_mensaje_de_exito(
                                webdriver_test_ux)

                            UtilsEvaluaciones.esperar_aparicion_modal_de_exito(
                                webdriver_test_ux)
                            UtilsEvaluaciones.esperar_desaparicion_modal_exito(
                                webdriver_test_ux)
                            break

            json_eval = UtilsEvaluaciones.establecer_output_status_step(
                json_eval, 4, 0, True,
                const_claro_drive.MSG_OUTPUT_BORRADO_ARCHIVO_EXITOSO)

        except NoSuchElementException as e:
            msg_output = const_claro_drive.MSG_OUTPUT_BORRADO_ARCHIVO_SIN_EXITO.format(
                e.msg)
            json_eval = UtilsEvaluaciones.establecer_output_status_step(
                json_eval, 4, 0, False, msg_output)

        except ElementClickInterceptedException as e:
            msg_output = const_claro_drive.MSG_OUTPUT_BORRADO_ARCHIVO_SIN_EXITO.format(
                e.msg)
            json_eval = UtilsEvaluaciones.establecer_output_status_step(
                json_eval, 4, 0, False, msg_output)

        except TimeoutException as e:
            msg_output = const_claro_drive.MSG_OUTPUT_BORRADO_ARCHIVO_SIN_EXITO.format(
                e.msg)
            json_eval = UtilsEvaluaciones.establecer_output_status_step(
                json_eval, 4, 0, False, msg_output)

        except StaleElementReferenceException as e:
            msg_output = const_claro_drive.MSG_OUTPUT_BORRADO_ARCHIVO_SIN_EXITO.format(
                e.msg)
            json_eval = UtilsEvaluaciones.establecer_output_status_step(
                json_eval, 4, 0, False, msg_output)

        except ElementNotInteractableException as e:
            msg_output = const_claro_drive.MSG_OUTPUT_BORRADO_ARCHIVO_SIN_EXITO.format(
                e.msg)
            json_eval = UtilsEvaluaciones.establecer_output_status_step(
                json_eval, 4, 0, False, msg_output)

        json_eval = UtilsEvaluaciones.finalizar_tiempos_en_step(
            json_eval, 4, tiempo_step_inicio, fecha_inicio)

        return json_eval
コード例 #21
0
ファイル: GetDailyWord.py プロジェクト: VicoandMe/Daily_Word
def GetDailyWord():
    capabilities = {
        'loggingPrefs': {},
        'xwalkOptions': {
            'binary': '/usr/bin/xwalk',
            'debugPort': '12450'
        }
    }
    driver = WebDriver('http://127.0.0.1:9515',
                       desired_capabilities=capabilities,
                       keep_alive=True)

    driver.get("http://cn.bing.com/dict/")

    word = driver.find_element_by_class_name('client_daily_word_en')
    word_text = word.text

    pronounce = driver.find_elements_by_class_name('client_daily_word_pn_pn')
    pronounce_text = []
    pronounce_text.append(pronounce[0].text)
    pronounce_text.append(pronounce[1].text)

    WriteWordList(word_text + " " + pronounce[0].text + " " +
                  pronounce[1].text)
    audio = driver.find_elements_by_class_name('client_aud_o')
    audio1_onmouseover = audio[0].get_attribute('onmouseover')
    audio1_onclick = audio[0].get_attribute('onclick')
    DownLoad_mp3(audio[0].get_attribute("onclick").split('\'')[1],
                 word_text + "_US")

    audio2_onmouseover = audio[1].get_attribute('onmouseover')
    audio2_onclick = audio[1].get_attribute('onclick')
    DownLoad_mp3(audio[1].get_attribute("onclick").split('\'')[1],
                 word_text + "_UK")

    translate = driver.find_element_by_class_name('client_daily_word_zh')
    translate_text = translate.text

    picture1_src = driver.find_element_by_id("emb1").get_attribute('src')
    picture2_src = driver.find_element_by_id("emb2").get_attribute('src')
    picture3_src = driver.find_element_by_id("emb3").get_attribute('src')
    DownLoad_jpg(picture1_src, word_text + '1')
    DownLoad_jpg(picture2_src, word_text + '2')
    DownLoad_jpg(picture3_src, word_text + '3')

    html_src = "<head>\
<meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\" />\
<title>Daily word</title>\
<link rel=\"stylesheet\" type=\"text/css\" href=\"daily-word/daily.css\"></link>\
</head>\
<body>\
<div class=\"client_daily_word_content\">\
<div class=\"client_daily_words_bar\">\
  <div class=\"client_daily_word_en\">\
    <a id=\"word\" href=\"http://bing.com.cn/dict/search?q=" + word_text + "\"h=\"ID=Dictionary,5014.1\">" + word_text + "</a>\
  </div>\
  <div class=\"client_daily_word_pn\">\
    <div class=\"client_daily_word_pn_pn\" lang=\"en\">" + pronounce_text[
        0] + "</div>\
    <div class=\"client_daily_word_pn_audio\">\
      <div class=\"client_icon_container\">\
	<audio id=\"us_pronun\" src=./daily-word/mp3/" + word_text + "_US.mp3" + " controls=\"contrils\"></audio>\
	</a>\
      </div>\
    </div>\
  </div>\
  <div class=\"client_daily_word_pn\">\
    <div class=\"client_daily_word_pn_pn\" lang=\"en\">" + pronounce_text[
            1] + "</div>\
    <div class=\"client_daily_word_pn_audio\">\
      <div class=\"client_icon_container\">\
	<audio id=\"us_pronun\" src=./daily-word/mp3/" + word_text + "_UK.mp3" + " controls=\"contrils\"></audio>\
	</a>\
      </div>\
    </div>\
  </div>\
  <div class=\"client_daily_word_zh\">" + translate_text + "</div>\
</div>\
<div class=\"client_daily_pic_bar\">\
  <a href=\"http://bing.com.cn/dict/search?q=" + word_text + "\"class=\"client_daily_pic_item\" target=\"_blank\" h=\"ID=Dictionary,5017.1\">\
    <img class=\"rms_img\" height=\"80\" id=\"emb1\" src=\"" + "./daily-word/picture/" + word_text + '1' + ".jpg" + "\" width = \"80\" />\
  </a>\
  <a href=\"http://bing.com.cn/dict/search?q=" + word_text + "\"class=\"client_daily_pic_item\" target=\"_blank\" h=\"ID=Dictionary,5017.1\">\
    <img class=\"rms_img\" height=\"80\" id=\"emb2\" src=\"" + "./daily-word/picture/" + word_text + '2' + ".jpg" + "\" width = \"80\" />\
  </a>\
  <a href=\"http://bing.com.cn/dict/search?q=" + word_text + "\"class=\"client_daily_pic_item\" target=\"_blank\" h=\"ID=Dictionary,5017.1\">\
    <img class=\"rms_img\" height=\"80\" id=\"emb3\" src=\"" + "./daily-word/picture/" + word_text + '3' + ".jpg" + "\" width = \"80\" />\
  </a>\
</div>\
</div>\
</div>\
<script src=\"daily-word/daily.js\"></script>\
</body>\
<html>\
"

    with open(word_text + ".html", "w+") as fp:
        html_src = html_src.encode('utf-8')
        fp.write(html_src)
コード例 #22
0
    def esperar_carga_total_de_archivo(webdriver: WebDriver,
                                       tiempo_step_inicio,
                                       tiempo_de_espera: int = 720):
        tiempo_inicial_ejecucion_de_funcion = Temporizador.obtener_tiempo_timer(
        )
        tiempo_step_inicio = Temporizador.obtener_tiempo_timer()
        tiempo_transcurrido = 0
        se_cargo_correctamente_el_fichero = False
        mensaje_exception = 'Han transcurrido mas de 12 minutos, sin cargar correctamente el archivo dentro del ' \
                            'portal de Claro Drive'
        numero_de_cancelaciones_de_descargas = 0

        while tiempo_transcurrido < tiempo_de_espera:
            # en cada iteracion espera al menos un segundo
            time.sleep(1)
            tiempo_transcurrido = Temporizador.obtener_tiempo_timer(
            ) - tiempo_inicial_ejecucion_de_funcion
            modal_de_exito = webdriver.find_elements_by_xpath(
                '//div[@class="up-file-actions isDone"]')
            modal_archivo_duplicado = webdriver.find_elements_by_class_name(
                'oc-dialog')

            if len(modal_de_exito) == 1:
                se_cargo_correctamente_el_fichero = True
                break
            elif len(modal_archivo_duplicado) > 0:
                try:
                    modal_archivo_duplicado = webdriver.find_element_by_class_name(
                        'oc-dialog')

                    check_box_all_files = HtmlActions.webdriver_wait_presence_of_element_located(
                        modal_archivo_duplicado,
                        5,
                        xpath=
                        '//label[@for="checkbox-allnewfiles"][text()="Archivos Nuevos"]'
                    )

                    HtmlActions.click_html_element(
                        check_box_all_files,
                        xpath=
                        '//label[@for="checkbox-allnewfiles"][text()="Archivos Nuevos"]'
                    )

                    boton_continuar = HtmlActions.webdriver_wait_element_to_be_clickable(
                        modal_archivo_duplicado, class_name='continue')

                    HtmlActions.click_html_element(boton_continuar,
                                                   class_name='continue')

                    HtmlActions.webdriver_wait_until_not_presence_of_element_located(
                        webdriver, class_name='oc-dialog')
                    continue
                except ElementNotInteractableException:
                    continue
                except NoSuchElementException:
                    continue
                except TimeoutException:
                    continue
                except ElementClickInterceptedException:
                    continue

            # print('entrando al header')
            header = webdriver.find_elements_by_class_name('up-header')

            if len(header) > 0:
                mensaje_de_carga = header[0]
                mensaje_de_carga = mensaje_de_carga.find_elements_by_tag_name(
                    'span')

                if len(mensaje_de_carga) > 0:
                    mensaje_de_carga = mensaje_de_carga[0]

                    if 'Se ha cancelado la carga' in mensaje_de_carga.text \
                            or '1 Subida en pausa' in mensaje_de_carga.text:

                        numero_de_cancelaciones_de_descargas = numero_de_cancelaciones_de_descargas + 1
                        # print('numero de cancelaciones: {}'.format(numero_de_cancelaciones_de_descargas))
                        #
                        # print('se procede a dar clic en el boton de reupload')

                        try:

                            boton_reupload = HtmlActions.webdriver_wait_element_to_be_clickable(
                                webdriver, class_name='ResumeUploadOption')

                            HtmlActions.click_html_element(
                                boton_reupload,
                                class_name='ResumeUploadOption')
                            # print('se dio click')
                            tiempo_step_inicio = Temporizador.obtener_tiempo_timer(
                            )
                            time.sleep(1)

                            continue
                        except ElementNotInteractableException:
                            continue
                        except NoSuchElementException:
                            continue
                        except TimeoutException:
                            continue
                        except ElementClickInterceptedException:
                            continue

                    if numero_de_cancelaciones_de_descargas > 10:
                        se_cargo_correctamente_el_fichero = False
                        mensaje_exception = 'Ha sucedido un error durante la carga del archivo, se presenta el ' \
                                            'siguiente mensaje: {}'.format(mensaje_de_carga.text)
                        # # DEBUG
                        # path_debug_img = '/home/trjlha/scripts/ux/clarodrive/debug_screenshots/debug.png'
                        # webdriver.save_screenshot(path_debug_img)
                        break

        if se_cargo_correctamente_el_fichero:
            UtilsEvaluaciones.esperar_desaparicion_modal_exito(webdriver)
        else:
            raise TimeoutException(msg=mensaje_exception)

        # print('tiempo step inicio dentro de la funcion: {}'.format(tiempo_step_inicio))
        return tiempo_step_inicio
コード例 #23
0
def find_highscores_rows(browser: WebDriver) -> List[WebElement]:
    table = browser.find_element_by_class_name('gunz-table')
    tbody = table.find_element_by_tag_name('tbody')
    return tbody.find_elements_by_tag_name('tr')
コード例 #24
0
def get_database_details(
    driver: WebDriver,
    database_name: str,
) -> DatabaseDict:  # pragma: no cover
    """
    Get details of a database.
    """
    target_manager_url = 'https://developer.vuforia.com/vui/develop/databases'
    driver.get(target_manager_url)
    ten_second_wait = WebDriverWait(driver, 10)

    # This is a hack.
    #
    # Not all items are shown on the first page and we do not yet support going
    # through pages.
    #
    # In our use cases so far we always want the latest databases.
    #
    #
    # Therefore we sort by last modified date.
    time.sleep(2)
    date_modified_element = driver.find_element_by_id(
        'sort-by-last-modified-date', )
    date_modified_element.click()
    time.sleep(10)
    date_modified_element.click()

    time.sleep(2)
    database_name_xpath = "//span[text()='" + database_name + "']"

    ten_second_wait.until(
        expected_conditions.presence_of_element_located(
            (By.XPATH, database_name_xpath), ), )

    database_cell_element = ten_second_wait.until(
        expected_conditions.element_to_be_clickable(
            (By.XPATH, database_name_xpath), ), )

    database_cell_element.click()

    access_keys_tab_item = ten_second_wait.until(
        expected_conditions.presence_of_element_located(
            (By.LINK_TEXT, 'Database Access Keys'), ), )

    access_keys_tab_item.click()

    # Without this we sometimes get empty strings for the keys.
    time.sleep(1)

    client_access_key = driver.find_element_by_class_name(
        'client-access-key', ).text
    client_secret_key = driver.find_element_by_class_name(
        'client-secret-key', ).text
    server_access_key = driver.find_element_by_class_name(
        'server-access-key', ).text
    server_secret_key = driver.find_element_by_class_name(
        'server-secret-key', ).text

    return {
        'database_name': database_name,
        'server_access_key': str(server_access_key),
        'server_secret_key': str(server_secret_key),
        'client_access_key': str(client_access_key),
        'client_secret_key': str(client_secret_key),
    }