Esempio n. 1
0
 def login(self):
     # chrome_options = webdriver.ChromeOptions()
     # chrome_options.add_argument('--headless')
     # chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
     # chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
     # chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
     # chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
     # chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
     # chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
     # chromedriver = "/usr/bin/chromedriver"
     # driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=chromedriver)
     # driver.get(self.ip+'/html/index.html#/login')
     options = webdriver.FirefoxOptions()
     options.add_argument('-headless')
     driver = webdriver.Firefox(options=options)
     driver.get(self.ip)
     Wait(driver, 300).until(
         Expect.presence_of_element_located((By.ID, "userpassword_ctrl")))
     driver.find_element_by_id('userpassword_ctrl').send_keys(self.password)
     driver.find_element_by_id('loginbtn').click()
     Wait(driver, 300).until(
         Expect.presence_of_element_located((By.ID, "devicecontrol")))
     cookie = driver.get_cookies()
     driver.close()
     for cook in cookie:
         self.ss.cookies.set(name=cook.get('name'), value=cook.get('value'))
Esempio n. 2
0
def wait(time, string, mode):  # Wait for an element to be usable
    if mode == 'clickable':
        Wait(Manga.driver,
             time).until(EC.element_to_be_clickable((By.XPATH, string)))
    elif mode == 'presence':
        Wait(Manga.driver,
             time).until(EC.presence_of_element_located((By.XPATH, string)))
Esempio n. 3
0
 def wait_for_element_visible(self, *args):
     if len(args) == 1 and isinstance(args[0], WebElement):
         Wait(self.selenium,
              self.timeout).until(expected.visibility_of(args[0]))
     else:
         Wait(self.selenium, self.timeout).until(
             expected.visibility_of_element_located(args))
Esempio n. 4
0
def verify_close_nav(driver):
    nav_close_button = Wait(driver, 10).until(
        EC.visibility_of_element_located((By.ID, "nav-close")))
    assert nav_close_button.is_displayed()
    nav_close_button.click()
    nav_links = Wait(driver, 10).until(
        EC.invisibility_of_element_located((By.CLASS_NAME, "nav-panel-links")))
    assert not nav_links.is_displayed()
Esempio n. 5
0
 def click_operators_button(self):
     Wait(self.selenium, self.timeout).until(
         expected.element_to_be_clickable(self._operators_button_locator))
     self.selenium.find_element(*self._operators_button_locator).click()
     element = Wait(self.selenium, self.timeout).until(
         expected.visibility_of_element_located(
             (By.CSS_SELECTOR, '#os-operators-headline')))
     return element
Esempio n. 6
0
def login(username, password):
    browser = None
    try:
        if utitls.configJson().get("driver_type", "chrome") == "firefox":
            firefox_option = webdriver.FirefoxOptions()
            firefox_option.headless = True
            browser = webdriver.Firefox(firefox_options=firefox_option)
        else:
            chrome_options = webdriver.ChromeOptions()
            chrome_options.headless = True
            browser = webdriver.Chrome(chrome_options=chrome_options)

        browser.get('https://passport.bilibili.com/login')
        Wait(browser, 60).until(
            Expect.visibility_of_element_located((By.CLASS_NAME, "gt_slider")))
        username_input = browser.find_element_by_id("login-username")
        username_input.send_keys(username)
        password_input = browser.find_element_by_id("login-passwd")
        password_input.send_keys(password)

        retry_times = 0
        max_retry_times = utitls.configJson().get("login_retry_times", 3)
        while retry_times < max_retry_times:
            do_captcha(browser)
            Wait(browser, 20).until(
                Expect.visibility_of_element_located(
                    (By.CLASS_NAME, "gt_info_tip")))
            if Expect.visibility_of_element_located((By.CLASS_NAME, "gt_success"))  \
                    or Expect.visibility_of_element_located((By.ID, "banner_link")):
                break
            retry_times += 1
            Wait(browser, 10).until(
                Expect.invisibility_of_element_located(
                    (By.CLASS_NAME, "gt_fail")))
            time.sleep(1)
        if retry_times >= max_retry_times:
            return ""

        #check is login Success
        Wait(browser, 60).until(
            Expect.visibility_of_element_located((By.ID, "banner_link")))
        browser.get('https://link.bilibili.com/p/center/index')
        Wait(browser, 10).until(
            Expect.visibility_of_element_located((By.CLASS_NAME, "user")))
        time.sleep(5)  #wait for the cookies
        cookies = browser.get_cookies()
        cookies_str_array = []
        for cookie in cookies:
            cookies_str_array.append(cookie["name"] + "=" + cookie["value"])
        browser.quit()
        return ";".join(cookies_str_array)
    except Exception as e:
        utitls.myLogger(traceback.format_exc())
        utitls.myLogger(str(e))
        if browser is not None:
            browser.quit()
        return ""
Esempio n. 7
0
def test_skills_of_team(driver, skill):
    driver.get(url)
    skill_item = Wait(driver, 10).until(
        EC.visibility_of_element_located((By.CLASS_NAME, "skills-item")))
    driver.execute_script("arguments[0].scrollIntoView();", skill_item)
    Wait(driver, 10).until(lambda driver: driver.find_element_by_css_selector(
        ".skills-label.FI.animated.fadeIn").text is not None)
    skill_title = driver.find_element_by_css_selector(".skills-item." +
                                                      skill).text
    assert skill_title == skill_match[skill]
Esempio n. 8
0
def list_games_from_livescore(date_now,date_next):
    '''
    Поиск игра на livescore
    На входе значения периода, для расширения диапазона поиска
    '''
    url = 'http://www.livescore.in/free/721594/'
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument('--no-proxy-server')
    chrome_options.add_argument("--proxy-server='direct://'")
    chrome_options.add_argument("--proxy-bypass-list=*")
    driver = webdriver.Chrome(chrome_options=chrome_options)
    logging.info('Google Chrome run in mode --headless')
    driver.get(url)
    logging.info('URL - %s'%driver.current_url)
    # Now day
    logging.info('The process of downloading data for %s ...'%date_now)
    try:
        Wait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//span/a[text()="'+date_now[:-1]+'"]')))
    except TimeoutException as ex:
        logging.info('TimeoutException "date_now" - %s'%ex.message)
    page = driver.page_source
    tree = html.fromstring(page)
    day = tree.xpath('//span[@class="day today"]/span/a/text()')
    logging.info('Data for %s uploaded successfully'%day)
    event_games = []
    id_game = tree.xpath('//table[@class="soccer"]/tbody/tr/@id')
    for i in range(0,len(id_game)):
        t_home = tree.xpath('//*[@id="'+id_game[i]+'"]/td[3]/span/text()')[0]
        t_away = tree.xpath('//*[@id="'+id_game[i]+'"]/td[5]/span/text()')[0]
        event_games.append((id_game[i],t_home,t_away))
    logging.info('List of games for %s created. Count of games - %s'%(day,str(len(event_games))))
    # Next day
    logging.info('The process of downloading data for %s ...'%date_next)
    try:
        Wait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//span[@class="day today"]'))).click()
        Wait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//span[text()="'+date_next[:-1]+'"]'))).click()
        Wait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//span/a[text()="'+date_next[:-1]+'"]')))
    except TimeoutException as ex:
        logging.info('TimeoutException "date_next" - %s'%ex.message)
    page = driver.page_source
    tree = html.fromstring(page)
    day = tree.xpath('//span[@class="day today"]/span/a/text()')
    logging.info('Data %s uploaded successfully'%day)
    id_game = tree.xpath('//table[@class="soccer"]/tbody/tr/@id')
    for i in range(0,len(id_game)):
        t_home = tree.xpath('//*[@id="'+id_game[i]+'"]/td[3]/span/text()')[0]
        t_away = tree.xpath('//*[@id="'+id_game[i]+'"]/td[5]/span/text()')[0]
        event_games.append((id_game[i],t_home,t_away))
    logging.info('List of games for %s created. Total count of games - %s'%(day,str(len(event_games))))
    driver.quit()
    return event_games
Esempio n. 9
0
    def registration(self):
        self.driver.get(self.page)

        self.driver.find_element_by_id('user_username').send_keys(
            self.user.name)
        self.driver.find_element_by_id('user_email').send_keys(self.user.email)
        self.driver.find_element_by_id('user_password').send_keys(
            self.user.password)
        self.driver.find_element_by_id('user_password_confirmation').send_keys(
            self.user.password)
        self.driver.find_element_by_id('user_agreement').click()
        self.driver.find_element_by_name('commit').click()

        self.driver.get(self.mailinator)
        self.driver.find_element_by_id('inbox_field').send_keys(
            self.user.email)
        self.driver.find_element_by_id('inbox_button').click()

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

        string_path = '/html/body/main/section/ul/li[@class=\'all_message-item all_message-item-parent cf ng-scope\']'

        Wait(self.driver,
             50).until(ec.presence_of_element_located((By.XPATH, string_path)))
        elements = self.driver.find_elements_by_xpath(string_path)
        dev_by = None
        for e in elements:
            if 'Dev.by' in e.text:
                dev_by = e
        dev_by.click()

        Wait(self.driver,
             50).until(ec.presence_of_element_located((By.TAG_NAME, 'iframe')))

        frame = self.driver.find_element_by_id('msg_body')
        self.driver.switch_to_frame(frame)
        Wait(self.driver,
             50).until(ec.presence_of_element_located((By.TAG_NAME, 'p')))
        self.driver.find_element_by_link_text('подтвердить').click()

        import smtplib
        text = "You nickname = " + self.user.name + "\n\tpassword = "******"\n"
        server = smtplib.SMTP('smtp.gmail.com', 587)  # port 465 or 587
        server.starttls()
        server.login('*****@*****.**', 'pass')
        server.sendmail('*****@*****.**', self.user.email, text)
        server.close()

        self.driver.close()
Esempio n. 10
0
 def __init__(self, url):
     chrome_options = webdriver.ChromeOptions()
     chrome_options.add_argument('--start-maximized')
     self.driver = webdriver.Chrome(chrome_options=chrome_options)
     self.driver.get(url)
     self.wait = Wait(self.driver, 10)
     self.action = ActionChains(self.driver)
Esempio n. 11
0
def automation_web(driver):
    url = 'https://www.google.com/search?q=michael+jordan&source=lnms&tbm=isch&sa=X&sqi=2&ved=0ahUKEwiTkP3_6dPgAhUEdt4KHWp0AmcQ_AUIDigB&biw=1536&bih=722'
    driver.get(url)

    driver.find_element_by_xpath('//*[@id="hdtb-tls"]').click()
    driver.find_element_by_xpath('//*[@id="hdtbMenus"]/div/div[2]/div').click()
    driver.find_element_by_xpath('//*[@id="isz_lt"]/a').click()
    driver.find_element_by_xpath('//*[@id="iszlt_4mp"]').click()
    time.sleep(5)

    js = "var q=document.documentElement.scrollTop=100000"
    for i in range(0, 5):
        #将滚动条移动到页面的底部
        #Let the scoll move to the bottom in the website
        driver.execute_script(js)
        time.sleep(1)
        print('To the bottom ' + str(i) + ' time')
    Wait(driver, 5).until(
        Except.presence_of_all_elements_located((By.XPATH, '//*[@id="smb"]')))
    driver.find_element_by_xpath('//*[@id="smb"]').click()
    for _ in range(0, 5):
        driver.execute_script(js)
        time.sleep(1)
    # #将滚动条移动到页面的顶部
    # js = "var q=document.documentElement.scrollTop=0"
    # driver.execute_script(js)
    # time.sleep(3)
    # #若要对页面中的内嵌窗口中的滚动条进行操作,要先定位到该内嵌窗口,在进行滚动条操作
    # js = "var q=document.getElementById('id').scrollTop=100000"
    # # driver.execute_script(js)
    # time.sleep(3)

    # driver.close()

    print('========finish=======')
Esempio n. 12
0
def assert_num_of_files_are_displayed_in_file_browser(selenium, browser_id,
                                                      num):
    driver = selenium[browser_id]
    Wait(driver, WAIT_FRONTEND).until(
        lambda _: len(_get_items_from_file_list(driver)) == num,
        message='displayed number of files {} does not match expected {}'
        ''.format(len(_get_items_from_file_list(driver)), num))
Esempio n. 13
0
def is_present_in_file_list(selenium, browser_id, item_list, item_type):
    driver = selenium[browser_id]
    item_type = item_type.replace('directorie', 'directory')
    Wait(driver, WAIT_FRONTEND).until_not(
        lambda _: _not_in_file_list(driver, item_list, item_type),
        message='waiting for {:s} item/items '
        'to appear in file list'.format(item_list))
Esempio n. 14
0
def has_downloaded_file_content(selenium, tmpdir, file_name, content,
                                browser_id):
    driver = selenium[browser_id]
    downloaded_file = tmpdir.join(browser_id, 'download', file_name)

    # sleep waiting for file to finish downloading
    exist = False
    sleep_time = 5
    for _ in range(10):
        if not exist:
            time.sleep(sleep_time)
        else:
            break
        exist = downloaded_file.isfile()

    assert exist, 'file {} has not been downloaded'.format(file_name)

    def _check_file_content():
        with downloaded_file.open() as f:
            file_content = ''.join(f.readlines())
            return content == file_content

    Wait(driver, WAIT_BACKEND).until(
        lambda _: _check_file_content(),
        message='checking if downloaded file contains {:s}'.format(content))
Esempio n. 15
0
def wait_for_modal_to_disappear(selenium, browser_id, tmp_memory):
    driver = selenium[browser_id]
    modal = tmp_memory[browser_id]['window']['modal']
    Wait(driver, WAIT_BACKEND).until_not(
        lambda _: not staleness_of(modal) or modal.is_displayed(),
        message='waiting for modal to disappear')
    tmp_memory[browser_id]['window']['modal'] = None
Esempio n. 16
0
 def is_create_account_form_displayed(self):
     wait = Wait(self, timeout=3)
     try:
         result = wait.until(expected.visibility_of_element_located((self._create_account_form_locator)))
         return result
     except TimeoutException:
         return False
Esempio n. 17
0
 def hide_answer(self):
     assert self.is_answer_displayed, 'Answer is already hidden'
     answer = self.root.find_element(*self._answer_locator)
     self.root.find_element(*self._question_locator).click()
     # Wait for aria-hidden attribute value to determine when animation has finished.
     Wait(self.selenium, self.timeout).until(
         lambda m: answer.get_attribute('aria-hidden') == 'true')
def Main():
    driver = webdriver.Chrome(chromedriver)
    driver.wait = Wait(driver, 5)
    driver.get(PROPERTYLINK)
    ProcessPage1(driver)
    ProcessPage2(driver)
    dataLinkList = GetLinksFromPage3(driver)
Esempio n. 19
0
def test_automatically_show_first_sidebar(base_url, selenium,
                                          complete_firstrun):
    """ Tests that the first sidebar opens automatically"""
    # switch to browser chrome
    selenium.set_context('chrome')

    # ensure that add-on action button is added as soon as we leave firstrun
    Wait(selenium, 2).until(
        expected.presence_of_element_located(
            (By.ID, 'action-button--all-aboard-v1-all-aboard')))

    # enure that the sidebar is automatically shown on first notification
    Wait(selenium, 3).until(
        expected.presence_of_element_located((
            By.CSS_SELECTOR,
            '#content-deck #sidebar-box[sidebarcommand="viewWebPanelsSidebar"]'
        )))
Esempio n. 20
0
 def login(self, user):
     self.click_login()
     browser_id = BrowserID(self.selenium, self.timeout)
     browser_id.sign_in(user['email'], user['password'])
     Wait(self.selenium, self.timeout).until(
         EC.visibility_of_element_located(self._logout_menu_item_locator))
     from pages.user.user_profile_edit import UserProfileEditPage
     return UserProfileEditPage(self.base_url, self.selenium).wait_for_page_to_load()
Esempio n. 21
0
 def test_user_can_sign_in(self, fxa_account, selenium, click_login,
                           timeout):
     fxa = WebDriverFxA(selenium, timeout)
     fxa.sign_in(fxa_account.email, fxa_account.password)
     # We sometimes need to wait longer than the standard 10 seconds
     Wait(selenium, timeout).until(
         EC.visibility_of_element_located(
             self._fxa_logged_in_indicator_locator))
Esempio n. 22
0
def get_token_from_modal(selenium, browser_id, tmp_memory):
    driver = selenium[browser_id]
    modal = tmp_memory[browser_id]['window']['modal']
    token_box = modal.find_element_by_css_selector('input[readonly]')
    token = Wait(driver, WAIT_BACKEND).until(
        lambda _: token_box.get_attribute('value'),
        message='waiting for token to appear')
    tmp_memory[browser_id]['token'] = token
Esempio n. 23
0
def select_adaptive(driver):
    Wait(driver=driver, timeout=10, poll_frequency=2).until(
        ec.element_to_be_clickable((
            By.XPATH,
            "//span[@class='p-channel_sidebar__name'] // span[contains(text(), 'adaptive')]"
        ))).click()
    # Wait for menu creation
    driver.implicitly_wait(5)
    Wait(driver=driver, timeout=10, poll_frequency=2).until(
        ec.element_to_be_clickable(
            (By.XPATH, "//*[contains(text(), 'I am good for now, thank you!')]"
             ))).click()
    Wait(driver=driver, timeout=10, poll_frequency=2).until(
        ec.element_to_be_clickable((
            By.XPATH,
            "//button[@class='c-button c-button--danger c-button--medium c-dialog__go null--danger null--medium']"
        ))).click()
Esempio n. 24
0
def op_check_if_row_of_name_appeared_in_table(selenium, browser_id, name,
                                              caption):
    driver = selenium[browser_id]
    Wait(driver, MAX_REFRESH_COUNT *
         WAIT_BACKEND).until(lambda s: refresh_and_call(
             s, _check_for_presence_of_item_in_table, name, caption),
                             message='searching for exactly one {:s} '
                             'on {:s} list in table'.format(name, caption))
Esempio n. 25
0
def test_three_notifications_shown(base_url,
                                   selenium,
                                   complete_firstrun):
    """ Tests that three notifications are shown for a sidebar"""
    # switch to browser chrome
    selenium.set_context('chrome')

    # ensure that add-on action button is added as soon as we leave firstrun
    action = Wait(selenium, 2).until(
        expected.presence_of_element_located(
            (By.ID, 'action-button--all-aboard-v1-all-aboard')))

    # first sidebar is automatically shown on first notification so,
    # we use this as out indicator that the first notifications happened.
    Wait(selenium, 3).until(
        expected.presence_of_element_located((
            By.CSS_SELECTOR,
            '#content-deck #sidebar-box[sidebarcommand="viewWebPanelsSidebar"]')  # noqa E501
        ))

    # wait for the second notification to happen
    Wait(selenium, 15).until(
        lambda s: action.get_attribute('badge') == '1'
    )

    # click the action button, this should not stop
    # the third notification from happening
    action.click()
    assert action.get_attribute('badge') == ''

    # wait for the third notification to happen
    Wait(selenium, 15).until(
        lambda s: action.get_attribute('badge') == '1'
    )

    # clicking the action button does not affect the notification,
    # here it is simply used to reset the badge attrbiute to ""
    action.click()
    assert action.get_attribute('badge') == ''

    # there should not be a fourth notification
    with pytest.raises(TimeoutException):
        Wait(selenium, 15).until(
            lambda s: action.get_attribute('badge') == '1'
        )
Esempio n. 26
0
def wait_for_url(driver, url, timeout_in_seconds=30, optional_message=""):
    try:
        Wait(driver,
             timeout_in_seconds).until(expected_conditions.url_contains(url))
    except TimeoutException:
        error_message = "Url not found. Expected URL: {0}, current URL: {1}. {2}".format(
            url, driver.current_url, optional_message)
        Logger.log.append(error_message)
        raise AssertionError(error_message)
Esempio n. 27
0
def waitTillOpen(dv, secs=60, by=By.XPATH, value=None):
    '''
    等待页面打开
    dv:webdriver
    secs:等待最长时间(秒), 默认60s
    '''
    wosHomePath = '//a[@class="snowplow-banner-wosLogo"]'
    Wait(dv, secs).until(
        EC.presence_of_element_located((by, value if value else wosHomePath)))
Esempio n. 28
0
 def wait_and_reject_alert(self):
     """Wait for alert and rejects."""
     try:
         Wait(self.driver, TIME_OUT).until(ec.alert_is_present())
         self.driver.switch_to.alert.dismiss()
         logging.info("alert dismissed")
     except selenium_exceptions.TimeoutException:
         logging.error(
             "Could Not Find Alert Within The Permissible Time Limit")
Esempio n. 29
0
 def wait_and_accept_alert(self):
     """Wait and accept alert present on the page."""
     try:
         Wait(self.driver, TIME_OUT).until(ec.alert_is_present())
         self.driver.switch_to.alert.accept()
         logging.info("alert accepted")
     except selenium_exceptions.TimeoutException:
         logging.error(
             "Could Not Find Alert Within The Permissible Time Limit")
Esempio n. 30
0
def is_share_not_viewable(selenium, browser_id):
    driver = selenium[browser_id]
    old_page = driver.find_element_by_css_selector('html')
    Wait(driver, WAIT_BACKEND).until(
        staleness_of(old_page),
        message='waiting for public share view to disappear')
    assert not re.search(r'https?://.*?/public/shares(/.*)?',
                         driver.current_url), \
        r'user can see public share with url {}'.format(driver.current_url)