Ejemplo n.º 1
0
    def _download_files_from_url(self, url: str, path: str, driver: WebDriver):
        """
        Downloads all files from a given url into given path

        Parameters
        ----------
        url : str
            Url to download files from
        path : str
            Path to download files into
        driver : WebDriver
            Driver with download path preference

        """
        driver.get(url)
        table = driver.find_element_by_id('mainTable')
        # give buffer time to find element with id = 'mainTable'
        time.sleep(1)
        elements = table.find_elements_by_tag_name('a')
        missing_files = {}
        for element in elements:
            f_url = element.get_attribute('href')
            is_folder = 'default.aspx' in f_url and '#' not in f_url
            is_file = 'download.aspx' in f_url and '#' not in f_url
            if is_folder:
                print('Checking {} folder for updates...'.format(element.text))
                f_path = '{}/{}'.format(path, element.text)
                self._create_folders(path, element.text)
                self._download_files_from_url(f_url, f_path,
                                              self._get_driver(f_path))
            elif is_file:
                if element.text not in os.listdir(path):
                    missing_files[element.text] = f_url
        self._update_folder(missing_files, driver)
        driver.close()
Ejemplo n.º 2
0
def completeMorePromotionABC(browser: WebDriver, cardNumber: int):
    browser.find_element_by_xpath(
        '//*[@id="more-activities"]/div/mee-card[' + str(cardNumber) +
        ']/div/card-content/mee-rewards-more-activities-card-item/div/div[3]/a'
    ).click()
    time.sleep(1)
    browser.switch_to.window(window_name=browser.window_handles[1])
    time.sleep(8)
    counter = str(
        browser.find_element_by_xpath('//*[@id="QuestionPane0"]/div[2]').
        get_attribute('innerHTML'))[:-1][1:]
    numberOfQuestions = max([int(s) for s in counter.split() if s.isdigit()])
    for question in range(numberOfQuestions):
        browser.execute_script(
            'document.evaluate("//*[@id=\'QuestionPane' + str(question) +
            '\']/div[1]/div[2]/a[' + str(random.randint(1, 3)) +
            ']/div", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()'
        )
        time.sleep(5)
        browser.find_element_by_xpath(
            '//*[@id="AnswerPane' + str(question) +
            '"]/div[1]/div[2]/div[4]/a/div/span/input').click()
        time.sleep(3)
    time.sleep(5)
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name=browser.window_handles[0])
    time.sleep(2)
Ejemplo n.º 3
0
def driver(request):
    print('start fixture')
    chrome_driver = WebDriver(executable_path='D://selenium//chromedriver.exe')
    chrome_driver.implicitly_wait(3)
    yield chrome_driver
    print('stop fixture')
    chrome_driver.close()
Ejemplo n.º 4
0
def setup():
    print("------- start driver_fixture ---------")
    driver = WebDriver()
    driver.implicitly_wait(5)
    yield driver
    print("------- stop driver_fixture ---------")
    driver.close()
Ejemplo n.º 5
0
def downloadPdfPages(driver: WebDriver, date: str, n_pages: int,
                     pdf_name: str) -> bool:
    """
    Download all pages of a newspaper and merge them.

    It will create temporary pdf files to contain the pages, then merge
    the files and delete them. File will be named 'jornais/pdf/<date>.pdf'
    """
    print("Number of pages:", n_pages)
    files_to_merge = []

    everything_ok = True

    page_count = 0
    while page_count < n_pages:
        everything_ok_with_this_page = True

        print(f"Starting page ({page_count}/{n_pages-1})", getNow())
        if page_count > 0:
            openNextPage(driver)

        pdf_frame = getContentFrame(driver)
        pdf_source = pdf_frame.get_attribute("src")

        fname = f'jornais/temp-{str(date)}-{page_count}.pdf'

        if fileDownloaded(fname):
            files_to_merge.append(fname)
        else:
            if not downloadPdf(pdf_source, fname):
                everything_ok = False
                everything_ok_with_this_page = False
            else:
                files_to_merge.append(fname)

            if everything_ok_with_this_page and page_count == 0:
                n_pages_download = checkPagesDownloaded(fname)
                if n_pages_download > 1:
                    if n_pages_download != n_pages:
                        print(
                            "More than one page downloaded, but not all. Giving up on this file."
                        )
                        return False
                    else:
                        print("All pages in page one. Done.")
                        copyfile(fname, pdf_name)
                        os.remove(fname)
                        return True

        page_count += 1

    print("Merging pdf pages...")
    driver.close()
    mergePdfFiles(files_to_merge, pdf_name)

    print("Deleting temporary pdf")
    for file in files_to_merge:
        os.remove(file)

    return everything_ok
Ejemplo n.º 6
0
def parse_adidas_page(driver: WebDriver, url):
    driver.get(get_url_largest(url))
    time.sleep(3)
    logging.info("Get Down")
    test_adidas_down(driver, 20)
    logging.info("Get Down")
    url = driver.current_url
    logging.info("Get Url")
    num_pages = get_num_pages(driver)
    logging.info("Get Num Pages")
    sources = [driver.page_source]
    logging.info("Get Source")
    for i in range(2, num_pages+1):
        link = get_link_to_next_page(url, i)
        logging.info("Get Link To Next Page")
        driver.get(link)
        logging.info("Move to Link to Next Page")
        time.sleep(3)
        test_adidas_down(driver, 20)
        logging.info("Get Down")
        sources.append(driver.page_source)
        logging.info("Append source")
    driver.close()
    driver.quit()
    logging.info("Close Driver")
    logging.info("Start make_soup")
    product_list = [make_soup(source).find_all("div", class_="innercard")
                    for source in sources]
    logging.info("End make_soup")
    product_list = chain(*product_list)
    logging.info("Start parse all source")
    return map(parse_product, product_list)
Ejemplo n.º 7
0
def close_other_tabs(chrome: WebDriver):
    all_handles = chrome.window_handles
    while(len(all_handles) > 1):
        chrome.close()
        sleep(0.5)
        all_handles = chrome.window_handles
        chrome.switch_to.window(all_handles[-1])
def completePunchCard(browser: WebDriver, url: str, childPromotions: dict):
    browser.get(url)
    for child in childPromotions:
        if child['complete'] == False:
            if child['promotionType'] == "urlreward":
                browser.execute_script("document.getElementsByClassName('offer-cta')[0].click()")
                time.sleep(1)
                browser.switch_to.window(window_name = browser.window_handles[1])
                time.sleep(random.randint(13, 17))
                browser.close()
                time.sleep(2)
                browser.switch_to.window(window_name = browser.window_handles[0])
                time.sleep(2)
            if child['promotionType'] == "quiz":
                browser.execute_script("document.getElementsByClassName('offer-cta')[0].click()")
                time.sleep(1)
                browser.switch_to.window(window_name = browser.window_handles[1])
                time.sleep(8)
                counter = str(browser.find_element_by_xpath('//*[@id="QuestionPane0"]/div[2]').get_attribute('innerHTML'))[:-1][1:]
                numberOfQuestions = max([int(s) for s in counter.split() if s.isdigit()])
                for question in range(numberOfQuestions):
                    browser.execute_script('document.evaluate("//*[@id=\'QuestionPane' + str(question) + '\']/div[1]/div[2]/a[' + str(random.randint(1, 3)) + ']/div", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()')
                    time.sleep(5)
                    browser.find_element_by_xpath('//*[@id="AnswerPane' + str(question) + '"]/div[1]/div[2]/div[4]/a/div/span/input').click()
                    time.sleep(3)
                time.sleep(5)
                browser.close()
                time.sleep(2)
                browser.switch_to.window(window_name = browser.window_handles[0])
                time.sleep(2)
Ejemplo n.º 9
0
def test_yandex_search():
    driver = WebDriver(
        executable_path=
        "//Users//ivanrezv//PycharmProjects//Testwork//chromedriver")
    driver.get('https://yandex.ru')
    driver.find_element_by_xpath('//input[@id="text"]').send_keys("Тензор")

    # Проверка наличия таблицы с подсказками
    wait = WebDriverWait(driver, 2)
    element = wait.until(
        EC.visibility_of_element_located(
            (By.XPATH, "//div[contains(@class,'popup_visible')]")))
    suggest = driver.find_element_by_xpath(
        "//div[contains(@class,'popup_visible')]")
    print('\n', "Таблица с подсказками имеется - ", suggest.is_displayed())

    # Клик по кнопке поиска
    search_button = driver.find_element_by_xpath(
        '//button[@type="submit"]').click()

    # Проверка наличия сайта
    sleep(2)
    links = driver.find_elements_by_css_selector(
        '#search-result > .serp-item a.link > b')
    items = [elem.text.strip() for elem in links[:5]]
    if "tensor.ru" not in items:
        raise Exception('В первых пяти результатах нет сайта tensor.ru')
    else:
        print(" Сайт tensor.ru - присутствует в первых 5 элементах")

    driver.close()
    print("End of first task")
Ejemplo n.º 10
0
def browser():
    webDriver = WebDriver(
        executable_path="C://Windows//System32//chromedriver.exe")
    webDriver.implicitly_wait(20)
    webDriver.maximize_window()
    yield webDriver
    webDriver.close()
    webDriver.quit()
def browser():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if os.name == 'nt':
        _browser = WebDriver(os.path.join(dir_path, "chromedriver.exe"))
    else:
        _browser = WebDriver(os.path.join(dir_path, "chromedriver"))
    yield _browser
    _browser.close()
    _browser.quit()
Ejemplo n.º 12
0
 def testCalc(self):
   driver = WebDriver()
   bmi_calc = bmicalcpage(driver)
   bmi_calc.open()
   self.assertEqual(True, bmi_calc.is_loaded)
   bmi_calc.calculate('181','80')
   self.assertEqual('24.4', bmi_calc.bmi)
   self.assertEqual('Normal', bmi_calc.bmi_category)
   driver.close()
Ejemplo n.º 13
0
 def testCalc(self):
   driver = WebDriver()
   bmi_calc = bmicalcpage(driver)
   bmi_calc.open()
   self.assertEqual(True, bmi_calc.is_loaded)
   bmi_calc.calculate('181','80')
   self.assertEqual('24.4', bmi_calc.bmi)
   self.assertEqual('Normal', bmi_calc.bmi_category)
   driver.close()
def completeMorePromotionSearch(browser: WebDriver, cardNumber: int):
    browser.find_element_by_xpath('//*[@id="more-activities"]/div/mee-card[' + str(cardNumber) + ']/div/card-content/mee-rewards-more-activities-card-item/div/div[3]/a').click()
    time.sleep(1)
    browser.switch_to.window(window_name = browser.window_handles[1])
    time.sleep(random.randint(13, 17))
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name = browser.window_handles[0])
    time.sleep(2)
Ejemplo n.º 15
0
 def log_out(self, browser: WebDriver) -> None:
     """
     Logs user out of the main ASNB portal
     """
     self._wait()
     browser.find_element_by_link_text('LOG KELUAR').click()
     logging.info('🔒 Logged out gracefully')
     logging.info('💻 Closing browser in a second')
     self._wait()
     browser.close()
Ejemplo n.º 16
0
class Application:
    def __init__(self):
        self.wd = WebDriver()
        self.wd.implicitly_wait(10)
        self.backend = Backend(self)
        self.frontend = Frontend(self)

    def destroy(self):
        self.wd.close()
        self.wd.quit()
def completeDailySetSearch(browser: WebDriver, cardNumber: int):
    time.sleep(5)
    browser.find_element_by_xpath('//*[@id="daily-sets"]/mee-card-group[1]/div/mee-card[' + str(cardNumber) + ']/div/card-content/mee-rewards-daily-set-item-content/div/div[3]/a').click()
    time.sleep(1)
    browser.switch_to.window(window_name = browser.window_handles[1])
    time.sleep(random.randint(13, 17))
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name = browser.window_handles[0])
    time.sleep(2)
Ejemplo n.º 18
0
def exitUser(browser: WebDriver):
    print("退出当前用户")
    windows = browser.window_handles
    for window in windows[1:]:
        # 关闭除第一个窗口外的其它窗口
        browser.switch_to.window(window)
        browser.close()
    browser.switch_to.window(windows[0])
    quitBtn = browser.find_element_by_xpath("//a[@id='quit']")
    quitBtn.click()
    print("当前用户退出成功!")
def completeDailySetQuiz(browser: WebDriver, cardNumber: int):
    time.sleep(2)
    browser.find_element_by_xpath(
        '//*[@id="daily-sets"]/mee-card-group[1]/div/mee-card[' +
        str(cardNumber) +
        ']/div/card-content/mee-rewards-daily-set-item-content/div/div[3]/a'
    ).click()
    time.sleep(1)
    browser.switch_to.window(window_name=browser.window_handles[1])
    time.sleep(8)
    if not waitUntilQuizLoads(browser):
        resetTabs(browser)
        return
    browser.find_element_by_xpath('//*[@id="rqStartQuiz"]').click()
    waitUntilVisible(browser, By.XPATH,
                     '//*[@id="currentQuestionContainer"]/div/div[1]', 10)
    time.sleep(3)
    numberOfQuestions = browser.execute_script(
        "return _w.rewardsQuizRenderInfo.maxQuestions")
    numberOfOptions = browser.execute_script(
        "return _w.rewardsQuizRenderInfo.numberOfOptions")
    for question in range(numberOfQuestions):
        if numberOfOptions == 8:
            answers = []
            for i in range(8):
                if browser.find_element_by_id("rqAnswerOption" + str(
                        i)).get_attribute("iscorrectoption").lower() == "true":
                    answers.append("rqAnswerOption" + str(i))
            for answer in answers:
                browser.find_element_by_id(answer).click()
                time.sleep(5)
                if not waitUntilQuestionRefresh(browser):
                    return
            time.sleep(5)
        elif numberOfOptions == 4:
            correctOption = browser.execute_script(
                "return _w.rewardsQuizRenderInfo.correctAnswer")
            for i in range(4):
                if browser.find_element_by_id(
                        "rqAnswerOption" +
                        str(i)).get_attribute("data-option") == correctOption:
                    browser.find_element_by_id("rqAnswerOption" +
                                               str(i)).click()
                    time.sleep(5)
                    if not waitUntilQuestionRefresh(browser):
                        return
                    break
            time.sleep(5)
    time.sleep(5)
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name=browser.window_handles[0])
    time.sleep(2)
    def test_calc(self):
        driver = WebDriver()
        bmi_calc = bmicalcpage(driver)
        bmi_calc.open()
        self.assertEqual(True, bmi_calc.is_loaded)
        bmi_calc.calculate('181','80')
        self.assertEqual('24.4', bmi_calc.bmi)
        self.assertEqual('Normal', bmi_calc.bmi_category)
        driver.close()

        if __name__ == '__main__':
           unittest.main()
Ejemplo n.º 21
0
def resetTabs(browser: WebDriver):
    curr = browser.current_window_handle

    for handle in browser.window_handles:
        if handle != curr:
            browser.switch_to.window(handle)
            time.sleep(0.5)
            browser.close()
            time.sleep(0.5)

    browser.switch_to.window(curr)
    time.sleep(0.5)
    browser.get('https://account.microsoft.com/rewards/')
Ejemplo n.º 22
0
class Application:
    def __init__(self):
        self.driver = WebDriver()
        self.driver.implicitly_wait(2)
        self.driver.get(Config.main_page)
        self.common = Common(self)
        self.stf = Stf(self)
        self.common.get_seed()
        self.common.write_seed_to_file()

    def destroy(self):
        self.driver.close()
        self.driver.quit()
Ejemplo n.º 23
0
def get_job_items_per_tab(driver: WebDriver, main_container: dict):
    try:
        list_containers = driver.find_elements(By.CLASS_NAME,
                                               'list-container')[:-1]
        keys = list(main_container.keys())
        print("Fetching data...")
        for idx in range(len(list_containers)):
            job_list = []
            job_container = list_containers[idx].find_elements(
                By.TAG_NAME, 'div')[3]
            job_items = job_container.find_elements(By.TAG_NAME, 'a')

            for job_item in tqdm(job_items):
                driver.execute_script(
                    f"window.open('{job_item.get_attribute('href')}', '_blank');"
                )
                windows = driver.window_handles
                sleep(3)
                driver.switch_to.window(windows[1])
                driver.implicitly_wait(5)

                # create a Job object from form input fields
                company = driver.find_element(
                    By.XPATH,
                    "//input[@placeholder='Company']").get_attribute('value')
                job_title = driver.find_element(
                    By.XPATH,
                    "//input[@placeholder='+ add title']").get_attribute(
                        'value')
                location = driver.find_element(
                    By.XPATH,
                    "//input[@placeholder='+ add location']").get_attribute(
                        'value')
                description = driver.find_element(By.CLASS_NAME,
                                                  'ql-editor').text
                post_url = driver.find_element(
                    By.XPATH, "//p[@title='Post URL']/following-sibling::div"
                ).find_element(By.TAG_NAME, 'a').get_attribute('href')

                a_job = Job(company, job_title, post_url, location,
                            description)
                job_list.append(a_job.as_dict())
                driver.close()
                driver.switch_to.window(windows[0])

            main_container[keys[idx]] = job_list

    except Exception as err:
        print(f"Error getting job_container:" + str(err))
        sys.exit(2)
def completePromotionalItems(browser: WebDriver):
    try:
        item = getDashboardData(browser)["promotionalItem"]
        if (item["pointProgressMax"] == 100 or item["pointProgressMax"] == 200) and item["complete"] == False and item["destinationUrl"] == "https://account.microsoft.com/rewards":
            browser.find_element_by_xpath('//*[@id="promo-item"]/section/div/div/div/a').click()
            time.sleep(1)
            browser.switch_to.window(window_name = browser.window_handles[1])
            time.sleep(8)
            browser.close()
            time.sleep(2)
            browser.switch_to.window(window_name = browser.window_handles[0])
            time.sleep(2)
    except:
        pass
Ejemplo n.º 25
0
def info_take_from(brower: WebDriver, tag: str) -> List[str]:
    '''
    提取附近内容的店面信息
    :param brower: 浏览器状态
    :param tag: 标签,例如:美食,住宿
    :return: 列表元素是 每个页面的信息
    '''
    # 点击第一个搜索结果,再点击附近,输入搜索内容
    brower.find_element_by_xpath('//*[@id="card-1"]/div/ul/li[1]').click()
    sleep(1)
    brower.find_element_by_xpath(
        '//*[@id="generalinfo"]/div[1]/div[1]').click()
    sleep(1)
    around_input = brower.find_element_by_xpath('//*[@id="nearby-input"]')
    around_input.send_keys(tag)
    around_input.send_keys(Keys.ENTER)
    sleep(2)

    # 点击缩小页面布局
    # brower.find_element_by_xpath('//*[@id="map-operate"]/div[2]/div[2]/div[2]').click()
    # sleep(10)

    # 附近信息提取,还要点击页面提取下一个页面信息
    info = [brower.find_element_by_class_name('poilist').text]
    while True:
        if '米' in info[-1]:
            try:
                page_location = brower.find_element_by_xpath(
                    '//*[@id="poi_page"]/p')
                # 由于不同位置页面元素不同,选择最后一个页面按钮
                next_page = page_location.find_elements_by_tag_name('span')[-1]
                # 判断是否是最后一个页面按钮是否可以点击
                next_page_status = next_page.find_element_by_tag_name(
                    'a').get_attribute("onclick")
                if next_page_status is not None:
                    next_page.click()
                    sleep(2)
                    info.append(
                        brower.find_element_by_class_name('poilist').text)
                else:
                    break
            except NoSuchElementException as e:
                break
        else:
            break

    brower.close()
    if len(info) == 1 and '米' not in info[0]: info = []
    return info
Ejemplo n.º 26
0
def completeDailySetThisOrThat(browser: WebDriver, cardNumber: int):
    time.sleep(2)
    browser.find_element_by_xpath(
        '//*[@id="daily-sets"]/mee-card-group[1]/div/mee-card[' +
        str(cardNumber) +
        ']/div/card-content/mee-rewards-daily-set-item-content/div/div[3]/a'
    ).click()
    time.sleep(1)
    browser.switch_to.window(window_name=browser.window_handles[1])
    time.sleep(8)
    loaded = False
    while (loaded == False):
        try:
            browser.find_element_by_xpath('//*[@id="rqStartQuiz"]')
            loaded = True
        except:
            time.sleep(0.5)
    browser.find_element_by_xpath('//*[@id="rqStartQuiz"]').click()
    waitUntilVisible(browser, By.XPATH,
                     '//*[@id="currentQuestionContainer"]/div/div[1]', 10)
    time.sleep(3)
    for question in range(10):
        answerEncodeKey = browser.execute_script("return _G.IG")

        answer1 = browser.find_element_by_id("rqAnswerOption0")
        answer1Title = answer1.get_attribute('data-option')
        answer1Code = getAnswerCode(answerEncodeKey, answer1Title)

        answer2 = browser.find_element_by_id("rqAnswerOption1")
        answer2Title = answer2.get_attribute('data-option')
        answer2Code = getAnswerCode(answerEncodeKey, answer2Title)

        correctAnswerCode = browser.execute_script(
            "return _w.rewardsQuizRenderInfo.correctAnswer")

        if (answer1Code == correctAnswerCode):
            answer1.click()
            time.sleep(8)
        elif (answer2Code == correctAnswerCode):
            answer2.click()
            time.sleep(8)

    time.sleep(5)
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name=browser.window_handles[0])
    time.sleep(2)
Ejemplo n.º 27
0
def test_yandex_pic():
    driver = WebDriver(
        executable_path=
        "//Users//ivanrezv//PycharmProjects//Testwork//chromedriver")
    driver.get('https://yandex.ru')
    driver.find_element_by_xpath("//*[text()='Картинки']").click()
    driver.switch_to.window(driver.window_handles[1])

    # Проверка перехода в "Картинки"
    if driver.current_url != "https://yandex.ru/images/?utm_source=main_stripe_big":
        raise Exception("Перемещение на на тот сайт")
    else:
        print("\n", "Переход верный, ссылка корректная")

    # Обращение к первой категории
    driver.find_element_by_xpath(
        "//div[@class='PopularRequestList-Item PopularRequestList-Item_pos_0']"
    ).click()
    driver.implicitly_wait(5)
    images1 = driver.find_elements_by_class_name("serp-item__link")
    img_link = images1[0].get_attribute("href")

    # Открываем первую картинку
    driver.get(img_link)
    sleep(2)
    first_img_url = driver.current_url

    # Переходим ко второй
    action = ActionChains(driver)
    action.key_down(Keys.ARROW_RIGHT).key_up(Keys.ARROW_RIGHT).perform()
    sleep(2)

    # Переходим обратно к первой
    action = ActionChains(driver)
    action.key_down(Keys.ARROW_LEFT).key_up(Keys.ARROW_LEFT).perform()
    sleep(2)
    finally_check = driver.current_url

    # Проверка возврата на первую картинку
    if finally_check != first_img_url:
        raise Exception("Перемещение выполнено не на первую картинку")
    else:
        print("\n", "Все корректно, картинка верная")

    driver.close()
    driver.quit()
    print("End of second task")
Ejemplo n.º 28
0
class Application:
    def __init__(self, base_url="http://forum.attnauka.webd.pro"):
        self.wd = WebDriver()
        self.wd.implicitly_wait(2)
        self.base_url = base_url
        self.common = Common(self)
        self.login_page = LoginPage(self)
        self.main_page = MainPage(self)
        self.sub_page = SubPage(self)

    def destroy(self):
        self.wd.close()
        self.wd.quit()

    def open_home_page(self):
        wd = self.wd
        wd.get(self.base_url)
Ejemplo n.º 29
0
def completeDailySetThisOrThat(browser: WebDriver, cardNumber: int):
    time.sleep(2)
    browser.find_element_by_xpath(
        '//*[@id="daily-sets"]/mee-card-group[1]/div/mee-card[' +
        str(cardNumber) +
        ']/div/card-content/mee-rewards-daily-set-item-content/div/div[3]/a'
    ).click()
    time.sleep(1)
    browser.switch_to.window(window_name=browser.window_handles[1])
    time.sleep(8)
    browser.find_element_by_xpath('//*[@id="rqStartQuiz"]').click()
    waitUntilVisible(browser, By.XPATH,
                     '//*[@id="currentQuestionContainer"]/div/div[1]', 10)
    time.sleep(3)
    for question in range(10):
        answerEncodeKey = browser.execute_script("return _G.IG")

        answer1 = browser.find_element_by_id("rqAnswerOption0")
        answer1Title = answer1.get_attribute('data-option')
        answer1Code = browser.execute_script(
            "var IG = \"" + answerEncodeKey +
            "\"; function getAnswerCode(n){for (var r, t = 0, i = 0; i < n.length; i++) t += n.charCodeAt(i); return r = parseInt(IG.substr(IG.length - 2), 16), t += r, t.toString();} return getAnswerCode(\""
            + answer1Title + "\");")

        answer2 = browser.find_element_by_id("rqAnswerOption1")
        answer2Title = answer2.get_attribute('data-option')
        answer2Code = browser.execute_script(
            "var IG = \"" + answerEncodeKey +
            "\"; function getAnswerCode(n){for (var r, t = 0, i = 0; i < n.length; i++) t += n.charCodeAt(i); return r = parseInt(IG.substr(IG.length - 2), 16), t += r, t.toString();} return getAnswerCode(\""
            + answer2Title + "\");")

        correctAnswerCode = browser.execute_script(
            "return _w.rewardsQuizRenderInfo.correctAnswer")

        if (answer1Code == correctAnswerCode):
            answer1.click()
            time.sleep(8)
        elif (answer2Code == correctAnswerCode):
            answer2.click()
            time.sleep(8)

    time.sleep(5)
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name=browser.window_handles[0])
    time.sleep(2)
Ejemplo n.º 30
0
def completeDailySetQuiz(browser: WebDriver, cardNumber: int,
                         numberOfQuestions: int):
    time.sleep(2)
    browser.find_element_by_xpath(
        '//*[@id="daily-sets"]/mee-card-group[1]/div/mee-card[' +
        str(cardNumber) +
        ']/div/card-content/mee-rewards-daily-set-item-content/div/div[3]/a'
    ).click()
    time.sleep(1)
    browser.switch_to.window(window_name=browser.window_handles[1])
    time.sleep(8)
    browser.find_element_by_xpath('//*[@id="rqStartQuiz"]').click()
    waitUntilVisible(browser, By.XPATH,
                     '//*[@id="currentQuestionContainer"]/div/div[1]', 10)
    time.sleep(3)
    for question in range(numberOfQuestions):
        points = int((browser.find_elements_by_class_name('rqECredits')[0]
                      ).get_attribute("innerHTML"))
        answer = 0
        while (int((browser.find_elements_by_class_name('rqECredits')[0]
                    ).get_attribute("innerHTML")) == points):
            browser.find_element_by_id("rqAnswerOption" + str(answer)).click()
            time.sleep(5)
            answer += 1

            tries = 0
            while True:
                try:
                    browser.find_elements_by_class_name('rqECredits')[0]
                    break
                except IndexError:
                    if tries < 10:
                        tries += 1
                        time.sleep(0.5)
                    else:
                        browser.refresh()
                        tries = 0
                        time.sleep(5)

        time.sleep(5)
    time.sleep(5)
    browser.close()
    time.sleep(2)
    browser.switch_to.window(window_name=browser.window_handles[0])
    time.sleep(2)
Ejemplo n.º 31
0
    def to_xiami(cls,
                 driver: WebDriver,
                 url_src_playlists: list,
                 _from: int = 1,
                 transfer_entry: str = None):
        """

		:param driver:
		:param url_src_playlists:
		:param _from:
		:param transfer_entry: 虾米导入歌单页面url
		:return:
		"""
        if transfer_entry is None:
            driver.get('https://www.xiami.com/')
            # xiami-specific
            # handle 签到页面
            time.sleep(1)
            WebDriverWait(driver, 15, 0.5).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, 'div.user div.avatar img')))
            my_music_ele = driver.find_element_by_partial_link_text('我的音乐')
            my_music_ele.click()
            time.sleep(1)

            WebDriverWait(driver, 15, 0.5).until(
                EC.presence_of_element_located(
                    (By.XPATH, "//div[starts-with(text(), '导入歌单')]")))

            import_ele = driver.find_element_by_xpath(
                "//div[starts-with(text(), '导入歌单')]")
            import_ele.click()
            # 导入歌单会在新标签打开,使绕过失效
            driver.switch_to.window(driver.window_handles[1])
            url = driver.current_url
            driver.switch_to.window(driver.window_handles[0])
            driver.get(url)
            driver.switch_to.window(driver.window_handles[1])
            driver.close()
            driver.switch_to.window(driver.window_handles[0])
        else:
            driver.get(transfer_entry)

        cls.__transfer(driver, url_src_playlists, _from, 'xiami')
Ejemplo n.º 32
0
        length = driver.find_element(By.XPATH,
                                 "//table[contains(@class,'stripe')]//td[contains(.,'Length')]/following-sibling::td").text
        developer = driver.find_element(By.XPATH,
                                    "//table[contains(@class,'stripe')]//td[contains(.,'Developer')]/following-sibling::td").text
    except exceptions.NoSuchElementException:
        if title == None:
            title = "Dummy_title"
        if length == None:
            length = "Dummy_Length"
        if developer == None:
            developer = "dummy_dev"
    if len(driver.find_elements(By.XPATH, "//div[contains(@class,'releases')]//tbody/tr[contains(@class,'lang')]")) > 1:
        we = driver.find_elements(By.XPATH,
                                           "//div[contains(@class,'releases')]//tbody/tr[contains(@class,'lang') and .//acronym[@title='Japanese']]//following-sibling::tr[contains(@class,'lang')][1]//preceding-sibling::tr[not(contains(@class,'lang')) and not(contains(.,'Trial')) and not(contains(.,'Download')) and .//acronym[@title='Windows']]//td[contains(@class,'tc4')]//a")
        for y in we:
            release_URL.append(y.get_attribute("href"))
    else:
        we = driver.find_elements(By.XPATH, "//div[contains(@class,'releases')]//tbody/tr[contains(@class,'lang') and .//acronym[@title='Japanese']]//following-sibling::tr[not(contains(.,'Trial')) and not(contains(.,'Download')) and .//acronym[@title='Windows']]//td[contains(@class,'tc4')]//a")
        for y in we:
            release_URL.append(y.get_attribute("href"))
    try:
        english_patch = True if len(driver.find_elements(By.XPATH, "//div[contains(@class,'releases')]//tbody/tr[contains(@class,'lang') and .//acronym[@title='English']]//following-sibling::tr[contains(@class,'lang')][1]/preceding-sibling::tr[.//preceding-sibling::tr[.//acronym[@title='English']]][not(contains(.,'Trial')) and not(contains(.,'Download')) and .//acronym[@title='Windows']]//td[contains(@class,'tc4')]//a")) > 0 else False
    except exceptions.NoSuchElementException:
        english_patch = False
    english_out = unicode("True") if english_patch else unicode("False")
    crafted_output = unicode(title + " " + length + " " + developer + " English Patch Available: " + english_out + "\n\tRELEASES")
    vn_file.write(crafted_output.encode('utf8'))
    releaseHandler(release_URL)
vn_file.close()
driver.close()