def listing_type(driver, params):
    print(('Listing types:'
           '\n\tAll Listings (1)'
           '\n\tAuction (2)'
           '\n\tBuy It Now (3)'))
    user_input = input('Choose 1-3: ')

    if user_input == '1':
        driver.set_window_size(1440, 900)
        button = driver.find_element_by_xpath(r'//*[@title="All Listings"]')
        button.click()
        WebDriverWait(driver, 10).until(ec.title_contains(params))
    elif user_input == '2':
        driver.set_window_size(1440, 900)
        button = driver.find_element_by_xpath(r'//*[@title="Auction"]')
        button.click()
        WebDriverWait(driver, 10).until(ec.title_contains(params))
    elif user_input == '3':
        driver.set_window_size(1440, 900)
        button = driver.find_element_by_xpath(r'//*[@title="Buy It Now"]')
        button.click()
        WebDriverWait(driver, 10).until(ec.title_contains(params))
    else:
        print('{} does not appear to be a correct choice, please try again'.format(user_input))
        listing_type(driver, params)
Esempio n. 2
0
    def _do_signup(self):
        # Go to the webpage
        self.browser.get(self.url)
        wait = ui.WebDriverWait(self.browser, self.timeout)
        wait.until(expected_conditions.visibility_of_element_located(["id", "logo"]))

        # Log out any existing user
        if self.browser.find_elements_by_id("nav_logout"):
            nav = self.browser.find_element_by_id("nav_logout")
            if nav.is_displayed():
                self.browser.find_element_by_id("nav_logout").click()
                wait = ui.WebDriverWait(self.browser, self.timeout)
                wait.until(expected_conditions.title_contains(("Home")))

        # Go to the sign-up page
        wait = ui.WebDriverWait(self.browser, self.timeout)
        wait.until(expected_conditions.visibility_of_element_located(["id", "nav_signup"]))
        self.browser.find_element_by_id("nav_signup").click()
        wait = ui.WebDriverWait(self.browser, self.timeout)
        wait.until(expected_conditions.title_contains(("Sign up")))

        # Sign up (don't choose facility or group)
        wait = ui.WebDriverWait(self.browser, self.timeout)
        wait.until(expected_conditions.visibility_of_element_located(["id", "id_username"]))
        self.browser.find_element_by_id("id_username").send_keys(self.username)
        wait = ui.WebDriverWait(self.browser, self.timeout)
        wait.until(expected_conditions.visibility_of_element_located(["id", "id_password_first"]))
        self.browser.find_element_by_id("id_password_first").send_keys(self.password)
        self.browser.find_element_by_id("id_password_recheck").send_keys(self.password)
        self.browser.find_element_by_id("id_password_recheck").send_keys(Keys.TAB + Keys.RETURN)
        wait = ui.WebDriverWait(self.browser, self.timeout)
        wait.until(expected_conditions.visibility_of_element_located(["id", "logo"]))
Esempio n. 3
0
 def testExpectedConditionTitleContains(self, driver, pages):
     pages.load("blank.html")
     driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")
     WebDriverWait(driver, 1).until(EC.title_contains("not"))
     assert driver.title == 'not blank'
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.title_contains("blanket"))
Esempio n. 4
0
 def test_login_and_post(self):
     # Go to the coop home page  
     self.driver.get("https://bc.libraries.coop/")
     # Log in
     self.driver.find_element_by_id("loginbtn").click()
     usernameField_present = EC.presence_of_element_located((By.ID, 'user_login'))
     WebDriverWait(self.driver, 10).until(usernameField_present)
     self.driver.find_element_by_id("user_login").send_keys(self.config['account']['username'])
     time.sleep(2)
     self.driver.find_element_by_id("user_pass").send_keys(self.config['account']['password'])
     time.sleep(2)
     self.driver.find_element_by_id("user-submit").click()
     time.sleep(2)
     # Navigate to My Dashboard
     self.driver.find_element_by_id("loginbtn").click()
     dashboardButton_present = EC.presence_of_element_located((By.LINK_TEXT, 'My Dashboard'))
     WebDriverWait(self.driver, 10).until(dashboardButton_present)
     self.driver.find_element_by_link_text("My Dashboard").click()
     WebDriverWait(self.driver, 10).until(EC.title_contains("Dashboard |"))
     # Navigate to test group, write and publish a post
     self.driver.find_element_by_xpath("//span[@class='group-title']").click()
     WebDriverWait(self.driver, 10).until(EC.title_contains("Home | Maple Public Library |"))
     self.driver.find_element_by_xpath("//textarea[@id='whats-new'][@name='whats-new']").send_keys(
         "This is a test post by Selenium Webdriver")
     self.driver.find_element_by_xpath(
         "//input[@id='aw-whats-new-submit']").send_keys("\n") # NOTE: Need to send "\n" instead of click for some weird wordpress buttons..
     # Check that the post is present, then delete it
     post_present = EC.presence_of_element_located((
         By.XPATH, "//div[@class='activity-inner']/p[text()='This is a test post by Selenium Webdriver']/../../div[@class='activity-meta']/a[text()='Delete']"))
     WebDriverWait(self.driver, 10).until(post_present)
     self.driver.find_element_by_xpath(
         "//div[@class='activity-inner']/p[text()='This is a test post by Selenium Webdriver']/../../div[@class='activity-meta']/a[text()='Delete']").send_keys("\n")
Esempio n. 5
0
 def test_register_as_institution(self):
     # Go to the bcla home page  
     self.driver.get("https://dev.bclaconnect.ca")
     WebDriverWait(self.driver, 10).until(EC.title_contains("BCLA Connect"))
     # Hover over myBCLA button, click join button
     mouse = webdriver.ActionChains(self.driver)
     myBCLA = self.driver.find_element_by_xpath("//a[@href='/mybcla']")
     mouse.move_to_element(myBCLA).perform()
     joinButton_present = EC.presence_of_element_located((By.XPATH, "//a[@href='/membership/join-bcla/'][@class='bcla-login-link']"))
     WebDriverWait(self.driver, 10).until(joinButton_present)
     self.driver.find_element_by_xpath("//a[@href='/membership/join-bcla/'][@class='bcla-login-link']").click()
     # Choose institutional membership
     WebDriverWait(self.driver, 10).until(EC.title_contains("Join BCLA |"))
     self.driver.find_element_by_link_text("Institutional Membership").click()
     WebDriverWait(self.driver, 10).until(EC.title_contains("Institutional Membership"))
     # Fill in form
     self.driver.find_element_by_id("CIVICRM_QFID_490_16").click()
     randomString = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(5))
     mailAddress = randomString + '@mailinator.com'
     self.driver.find_element_by_id("email-5").send_keys(mailAddress)
     usrName = self.config['account']['username'] + randomString
     self.driver.find_element_by_id("onbehalf_organization_name").send_keys(usrName)
     self.driver.find_element_by_id("onbehalf_phone-3-1").send_keys(self.config['account']['phone'])
     self.driver.find_element_by_id("onbehalf_email-3").send_keys(mailAddress)
     self.driver.find_element_by_id("onbehalf_street_address-3").send_keys(self.config['account']['address'])
     self.driver.find_element_by_id("onbehalf_city-3").send_keys(self.config['account']['city'])
     self.driver.find_element_by_id("onbehalf_postal_code-3").send_keys(self.config['account']['postal'])
     self.driver.find_element_by_id("cms_name").send_keys(usrName)
     self.driver.find_element_by_id("cms_pass").send_keys(self.config['account']['password'])
     self.driver.find_element_by_id("cms_confirm_pass").send_keys(self.config['account']['password'])
     self.driver.find_element_by_id("first_name").send_keys(self.config['account']['firstname'])
     self.driver.find_element_by_id("last_name").send_keys(self.config['account']['lastname'])
     self.driver.find_element_by_xpath("//a[@class='crm-credit_card_type-icon-mastercard']").click()
     self.driver.find_element_by_id("credit_card_number").send_keys('5555555555554444')
     self.driver.find_element_by_id("cvv2").send_keys('066')
     self.driver.find_element_by_xpath("//select[@id='credit_card_exp_date_M']/option[text()='Jan']").click()
     self.driver.find_element_by_xpath("//select[@id='credit_card_exp_date_Y']/option[text()='2026']").click()
     self.driver.find_element_by_id("billing_first_name").send_keys(self.config['account']['firstname'])
     self.driver.find_element_by_id("billing_last_name").send_keys(self.config['account']['lastname'])
     self.driver.find_element_by_id("billing_street_address-5").send_keys(self.config['account']['address'])
     self.driver.find_element_by_id("billing_city-5").send_keys(self.config['account']['city'])
     self.driver.find_element_by_id("billing_postal_code-5").send_keys(self.config['account']['postal'])
     self.driver.find_element_by_id("CIVICRM_QFID_0_12").click()
     self.driver.find_element_by_id("_qf_Main_upload-bottom").click()
     #Click "make payment"
     paymentButton_present = EC.presence_of_element_located((By.ID, "_qf_Confirm_next-top"))
     WebDriverWait(self.driver, 10).until(paymentButton_present)
     self.driver.find_element_by_id("_qf_Confirm_next-top").click()
     # Check that payment went through
     WebDriverWait(self.driver, 60).until(EC.title_contains("Welcome to BCLA"))
     src = self.driver.page_source
     text_found = re.search(r'Your transaction has been processed successfully. Please print this page for your records.', src)
     self.assertNotEqual(text_found, None)
     # Check the email was sent and received
     self.driver.get("https://www.mailinator.com/inbox2.jsp?public_to=" + randomString + "#/#public_maildirdiv")
     WebDriverWait(self.driver, 30).until(EC.title_contains("Mailinator"))
     print("Mailbox at:")
     print("https://www.mailinator.com/inbox2.jsp?public_to=" + randomString + "#/#public_maildirdiv")
     print("Should contain a welcome message and receipt for an institutional membership.")
Esempio n. 6
0
 def testExpectedConditionTitleContains(self, driver, pages):
     if driver.capabilities['browserName'] == 'firefox' and driver.w3c:
         pytest.xfail("Marionette issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1297551")
     pages.load("blank.html")
     driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")
     WebDriverWait(driver, 1).until(EC.title_contains("not"))
     assert driver.title == 'not blank'
     with pytest.raises(TimeoutException):
         WebDriverWait(driver, 0.7).until(EC.title_contains("blanket"))
Esempio n. 7
0
	def testLogin(self):
		driver = self.browser
		driver.get('https://localhost:8000/formular/')
		element = WebDriverWait(driver, 10).until(EC.title_contains('OpenID'))
		sub = driver.find_element_by_id('j_username').send_keys(id)
		driver.find_element_by_id('j_password').send_keys(password)
		driver.find_element_by_xpath("html/body/div/div/div/form/div/input").click()
		element = WebDriverWait(driver, 10).until(EC.title_contains('HPC'))
		self.assertIn('HPC', driver.title)
 def testExpectedConditionTitleContains(self):
     self._loadPage("blank")
     self.driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")
     WebDriverWait(self.driver, 1).until(EC.title_contains("not"))
     self.assertEqual(self.driver.title, 'not blank')
     try:
         WebDriverWait(self.driver, 0.7).until(EC.title_contains("blanket"))
         self.fail("Expected TimeoutException to have been thrown")
     except TimeoutException as e:
         pass
 def log_user_in(self, username, password):
     self.browser.get(self.url)
     self.wait.until(EC.title_contains('Log in'))
     login_box = self.wait.until(
         EC.presence_of_element_located((By.ID, 'id_username')))
     login_box.send_keys(username)
     password_box = self.wait.until(
         EC.presence_of_element_located((By.ID, 'id_password')))
     password_box.send_keys(password)
     password_box.send_keys(Keys.ENTER)
     self.wait.until(EC.title_contains('Facility Management'))
     self.logged_in = True
Esempio n. 10
0
 def _do_login_step_1(self, args):
     wait = ui.WebDriverWait(self.browser, self.timeout)
     wait.until(expected_conditions.title_contains(("Log in")))
     wait = ui.WebDriverWait(self.browser, self.timeout)
     wait.until(expected_conditions.element_to_be_clickable((By.ID, "id_username")))         
     elem = self.browser.find_element_by_id("id_username")
     elem.send_keys(args["username"])
     elem = self.browser.find_element_by_id("id_password")
     elem.send_keys(args["password"])
     elem.send_keys(Keys.RETURN)
     wait = ui.WebDriverWait(self.browser, self.timeout)
     wait.until(expected_conditions.title_contains(("User report")))
Esempio n. 11
0
 def test_aregister_as_individual(self):
     # This test creates the account that "test_donate_as_individual" uses, hence the "a" in the name, so Selenium runs it first
     # Go to the bcla home page  
     self.driver.get("https://dev.bclaconnect.ca")
     WebDriverWait(self.driver, 10).until(EC.title_contains("BCLA Connect"))
     # Hover over myBCLA button, click join button
     mouse = webdriver.ActionChains(self.driver)
     myBCLA = self.driver.find_element_by_xpath("//a[@href='/mybcla']")
     mouse.move_to_element(myBCLA).perform()
     joinButton_present = EC.presence_of_element_located((By.XPATH, "//a[@href='/membership/join-bcla/'][@class='bcla-login-link']"))
     WebDriverWait(self.driver, 10).until(joinButton_present)
     self.driver.find_element_by_xpath("//a[@href='/membership/join-bcla/'][@class='bcla-login-link']").click()
     # Choose individual membership
     WebDriverWait(self.driver, 10).until(EC.title_contains("Join BCLA |"))
     self.driver.find_element_by_link_text("Individual Membership").click()
     WebDriverWait(self.driver, 10).until(EC.title_contains("Individual Membership |"))
     # Fill in form
     mailAddress = BCLATests.individualRandomString + '@mailinator.com'
     self.driver.find_element_by_id("email-5").send_keys(mailAddress)
     self.driver.find_element_by_id("cms_name").send_keys(self.config['account']['username'] + BCLATests.individualRandomString)
     self.driver.find_element_by_id("cms_pass").send_keys(self.config['account']['password'])
     self.driver.find_element_by_id("cms_confirm_pass").send_keys(self.config['account']['password'])
     self.driver.find_element_by_id("first_name").send_keys(self.config['account']['firstname'])
     self.driver.find_element_by_id("last_name").send_keys(self.config['account']['lastname'])
     self.driver.find_element_by_id("street_address-Primary").send_keys(self.config['account']['address'])
     self.driver.find_element_by_id("city-Primary").send_keys(self.config['account']['city'])
     #self.driver.find_element_by_xpath("//div[@id='s2id_state_province-Primary']").click()
     self.driver.find_element_by_id("postal_code-Primary").send_keys(self.config['account']['postal'])
     self.driver.find_element_by_xpath("//a[@class='crm-credit_card_type-icon-mastercard']").click()
     self.driver.find_element_by_id("credit_card_number").send_keys('5555555555554444')
     self.driver.find_element_by_id("cvv2").send_keys('066')
     self.driver.find_element_by_xpath("//select[@id='credit_card_exp_date_M']/option[text()='Jan']").click()
     self.driver.find_element_by_xpath("//select[@id='credit_card_exp_date_Y']/option[text()='2026']").click()
     self.driver.find_element_by_id("CIVICRM_QFID_0_12").click()
     self.driver.find_element_by_id("_qf_Main_upload-bottom").click()
     #Click "make payment"
     paymentButton_present = EC.presence_of_element_located((By.ID, "_qf_Confirm_next-top"))
     WebDriverWait(self.driver, 10).until(paymentButton_present)
     self.driver.find_element_by_id("_qf_Confirm_next-top").click()
     # Check that payment went through
     WebDriverWait(self.driver, 60).until(EC.title_contains("Welcome to BCLA"))
     src = self.driver.page_source
     text_found = re.search(r'Your transaction has been processed successfully. Please print this page for your records.', src)
     self.assertNotEqual(text_found, None)
     # Check the email was sent and received
     self.driver.get("https://www.mailinator.com/inbox2.jsp?public_to=" + BCLATests.individualRandomString + "#/#public_maildirdiv")
     WebDriverWait(self.driver, 30).until(EC.title_contains("Mailinator"))
     print("Mailbox at:")
     print("https://www.mailinator.com/inbox2.jsp?public_to=" + BCLATests.individualRandomString + "#/#public_maildirdiv")
     print("Should contain a welcome message and receipt for an individual membership.")
     self.driver.quit()
Esempio n. 12
0
def get_auth_cookie(domain, login, password):

    # configure chrome
    options = Options()
    #options.add_argument('--headless')
    #options.add_argument('--disable-gpu')
    options.add_argument('--window-size=700,600')

    driver = webdriver.Chrome(chrome_options=options)

    # load the login page and wait until the title contains GitLab
    driver.get("https://{}/login".format(domain))
    WebDriverWait(driver, 10).until(EC.title_contains("GitLab"))

    # click on the gitlab button to continue
    gitlabElement = driver.find_element_by_partial_link_text("GitLab")
    gitlabElement.click()

    # wait for the sign in page to load
    WebDriverWait(driver, 10).until(EC.title_contains("Sign in"))

    # fill out the username
    emailElement = driver.find_element_by_id('username')
    emailElement.send_keys(login)

    # fill out the password
    passwordElement = driver.find_element_by_id('password')
    passwordElement.send_keys(password)

    # submit the form
    passwordElement.submit()

    # wait until the page loads
    WebDriverWait(driver, 600).until(EC.title_contains("User Settings"))

    # authorize mattermost to use your account
    #elementAuthorize = driver.find_element_by_name('commit')
    elementAuthorize = driver.find_element_by_css_selector('input.btn-success')
    elementAuthorize.click()

    WebDriverWait(driver, 600).until(EC.title_contains("Mattermost"))

    auth_cookie = None
    for cookie in driver.get_cookies():
        if cookie['name'] == 'MMAUTHTOKEN':
            auth_cookie = cookie

    driver.quit()

    return auth_cookie
Esempio n. 13
0
 def test_login_and_create_doc(self):
     # Go to the coop home page  
     self.driver.get("https://bc.libraries.coop/")
     # Log in
     self.driver.find_element_by_id("loginbtn").click()
     usernameField_present = EC.presence_of_element_located((By.ID, 'user_login'))
     WebDriverWait(self.driver, 10).until(usernameField_present)
     self.driver.find_element_by_id("user_login").send_keys(self.config['account']['username'])
     time.sleep(2)
     self.driver.find_element_by_id("user_pass").send_keys(self.config['account']['password'])
     time.sleep(2)
     self.driver.find_element_by_id("user-submit").click()
     time.sleep(2)
     # Go to Profile, Docs tab, click Create New Doc
     self.driver.find_element_by_id("loginbtn").click()
     profileButton_present = EC.presence_of_element_located((By.LINK_TEXT, 'My Profile'))
     WebDriverWait(self.driver, 10).until(profileButton_present)
     self.driver.find_element_by_link_text("My Profile").click()
     WebDriverWait(self.driver, 10).until(EC.title_contains("Profile |"))
     self.driver.find_element_by_id("user-docs").click()
     WebDriverWait(self.driver, 10).until(EC.title_contains("Docs |"))
     self.driver.find_element_by_id("bp-create-doc-button").click()
     # Fill in Doc creation form
     titleField_present = EC.presence_of_element_located((By.ID, 'doc-title'))
     WebDriverWait(self.driver, 10).until(titleField_present)
     self.driver.find_element_by_id("doc-title").send_keys("Selenium Test Document")
     self.driver.find_element_by_id("doc_content-html").click()
     contentField_present = EC.presence_of_element_located((By.XPATH, "//textarea[@id='doc_content'][@name='doc_content']"))
     WebDriverWait(self.driver, 10).until(contentField_present)
     self.driver.find_element_by_xpath("//textarea[@id='doc_content'][@name='doc_content']").send_keys(
         "This is a test document created to test site functionality with Selenium Webdriver.")
     self.driver.find_element_by_xpath("//select[@id='settings-read']/option[text()='The Doc author only']").click()
     # Save doc and check it was succesfully created
     self.driver.find_element_by_id("doc-edit-submit").click()
     src = self.driver.page_source
     text_found = re.search(r'Doc successfully created', src)
     self.assertNotEqual(text_found, None)
     # Delete the doc and check it was succesfully deleted
     self.driver.find_element_by_link_text("Edit").click()
     deleteButton_present = EC.presence_of_element_located((By.LINK_TEXT, 'Permanently Delete'))
     WebDriverWait(self.driver, 10).until(deleteButton_present)
     self.driver.find_element_by_link_text("Permanently Delete").click()
     alert = self.driver.switch_to_alert() # This will cause a warning, but the "newer" method of this does not work.
     alert.accept()
     time.sleep(2)
     src = self.driver.page_source
     text_found = re.search(r'Doc successfully deleted', src)
     self.assertNotEqual(text_found, None)
Esempio n. 14
0
def step_impl(context, url):
    context.driver.get(url)
    try:
        WebDriverWait(context.driver, 10).until(expected_conditions.title_contains("Wikipedia"))
    except TimeoutException:
        print("The %s page failed to load! FAIL" % url)
        context.failed = True
Esempio n. 15
0
    def _login(self):
        fb_login_button = self._css('.fb-login-button')

        self._assert_visible(fb_login_button)

        time.sleep(0.1)

        fb_login_button.click()

        wait = WebDriverWait(self.driver, 2)
        wait.until(window_opened)

        self.driver.switch_to_window(self.driver.window_handles[1])
        wait.until(lambda d: d.find_element_by_name('email'))

        email_input = self.driver.find_element_by_name('email')
        pass_input = self.driver.find_element_by_name('pass')

        email_input.send_keys('*****@*****.**')
        pass_input.send_keys('flowtestpass')
        pass_input.submit()

        self.driver.switch_to_window(self.driver.window_handles[0])

        wait = WebDriverWait(self.driver, 10)
        wait.until(EC.title_contains('Welcome'))
        wait.until(lambda d: d.find_element_by_class_name("transcript-text"))
Esempio n. 16
0
def test_github_project(driver):
    driver.get('https://github.com/meejah/txtorcon')

    body = driver.find_element_by_tag_name('body')

    # activate the "file finder"
    ActionChains(driver) \
        .move_to_element(body) \
        .click(on_element=body) \
        .send_keys_to_element(body, 't') \
        .perform()

    # wait up to 5 seconds until it's "actually" activated (which we
    # know because an element with a particular ID will be visible)
    finder = WebDriverWait(driver, timeout=5.0).until(
        EC.presence_of_element_located(
            (By.ID, "tree-finder-field")
        )
    )

    # now we press "down" three times, and return...
    ActionChains(driver) \
        .send_keys_to_element(finder, Keys.ARROW_DOWN) \
        .send_keys_to_element(finder, Keys.ARROW_DOWN) \
        .send_keys_to_element(finder, Keys.ARROW_DOWN) \
        .send_keys_to_element(finder, Keys.ENTER) \
        .perform()

    # ...which we confirm because this "should" have loaded the Dockerfile
    WebDriverWait(driver, 5.0).until(EC.title_contains('Dockerfile'))
Esempio n. 17
0
    def test_create_new_customer(self):
        # wait for 'Create an Account' to be clickable. click it
        # and wait for next page

        self.driver.find_element_by_link_text("ACCOUNT").click()

        # wait for 'My Account' link in menu
        my_account = WebDriverWait(self.driver, 10).until(
            expected_conditions.visibility_of_element_located(
                (By.LINK_TEXT, "My Account")
            )
        )
        my_account.click()

        # get 'Create Account' button
        # wait for element to be enabled
        create_account_button = WebDriverWait(self.driver, 10).until(
            expected_conditions.element_to_be_clickable(
                (By.LINK_TEXT, "CREATE AN ACCOUNT")
            )
        )

        # display new account
        create_account_button.click()

        WebDriverWait(self.driver, 10).until(
            expected_conditions.title_contains(
                "Create New Customer Account"
            )
        )
Esempio n. 18
0
 def share(self, path, target_email):
   url = "https://www.dropbox.com/"
   print 'Get access token from Dropbox'
   print 'Open auth url:', url
   browser = webdriver.PhantomJS(service_log_path=os.path.join(tempfile.gettempdir(), 'ghostdriver.log'), service_args=['--ignore-ssl-errors=true', '--ssl-protocol=tlsv1'])
   browser.get(url)
   try:
     wait = WebDriverWait(browser, 30)
     btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@id='sign-in']/a")))
     btn.click()
     email = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@id='login_email']")))
     email.send_keys(raw_input("Enter your Dropbox email:"))
     pwd = browser.find_element_by_xpath("//input[@id='login_password']") 
     pwd.send_keys(getpass.getpass("Enter your Dropbox password:"******"//a[text()='%s']" % path)))
     target_folder.click()
     wait.until(EC.title_contains("%s" % path))
     share_btn = browser.find_element_by_xpath("//a[@id='global_share_button']")
     share_btn.click()
     target = wait.until(EC.element_to_be_clickable((By.XPATH, "//form[@class='invite-more-form']//input[@spellcheck][@type='text']")))
     target.send_keys(target_email)
     confirm_btn = browser.find_element_by_xpath("//form[@class='invite-more-form']//input[@type='button'][1]")
     confirm_btn.click()
   except:
     print(browser.title)
     assert False
     # print(browser.current_url)
     # print(browser.page_source)    
     pass
def clickCompose(mainCfg,driver):

    try:
        # waiting for loading list of inbox messages
        subjectPath = '//tbody/tr/td[5]/div'
        WebDriverWait(driver, mainCfg['timeout']).until(EC.element_to_be_clickable((By.XPATH,subjectPath)))

    except selenium.common.exceptions.TimeoutException as err:

        # if there is no message in the list search for "no messages" message
        subjectPath = '//div/div/div[2]/div/div/div/div/div/div[2]/div/div'
        WebDriverWait(driver, mainCfg['timeout']).until(EC.element_to_be_clickable((By.XPATH,subjectPath)))

    # selecting compor
    selectPath = '//div/table/tbody/tr/td/table/tbody/tr[2]/td[2]/em/button'
    WebDriverWait(driver, mainCfg['timeout']).until(EC.element_to_be_clickable((By.XPATH,selectPath)))
    selectBtn = driver.find_element_by_xpath(selectPath)
    selectBtn.click()

    # wait for compor email window
    WebDriverWait(driver, mainCfg['timeout']).until( lambda driver: len(driver.window_handles) == 2 )

    windowCompose = driver.window_handles[-1]

    driver.switch_to_window(windowCompose)
    WebDriverWait(driver, mainCfg['timeout']).until(EC.title_contains('Compor mensagem:'))
    
    return windowCompose
Esempio n. 20
0
    def test_import_query(self):
        link = self.findLink("Import query from XML")
        self.assertIsNotNone(link)
        link.click()
        time.sleep(3)
        self.assertIn('Import Query', self.browser.title)
        input_box = self.elem('#xml')
        self.assertIsNotNone(input_box)
        query = ''.join([
            '<query model="testmodel" view="Bank.debtors.debt" sortOrder="Bank.debtors.debt asc">',
            '<constraint path="Bank.debtors.debt" op="&gt;" value="1000"/>',
            '</query>'
            ])

        input_box.send_keys(query)
        self.assertEquals('true', self.elem('#file').get_attribute('disabled'))
        self.elem('#importQueriesForm input[type="submit"]').click()
        wait = WebDriverWait(self.browser, 10)
        wait.until(EC.title_contains('Query builder'))

        self.assertEquals('Bank', self.elem('.typeSelected').text)
        constraints = self.elems('span.constraint')
        self.assertEquals(1, len(constraints))
        self.assertEquals('> 1000', constraints[0].text)
        self.assertEquals(1, len(self.browser.find_elements_by_class_name('viewpath')))
Esempio n. 21
0
 def _click_sign_in_button(self):
     """
     Clicks the Sign In button.
     """
     self._driver.find_element(*self._sign_in_button).click()
     self._wait.until(ec.title_contains(self.page_title), "The page does not contain the " + self.page_title + " title.")
     return self
Esempio n. 22
0
 def test_applicants_summary(self, driver):
     assert 'John Smith' in driver.page_source
     assert '>Full<' in driver.page_source
     assert 'Junior Smith' in driver.page_source
     assert '>Junior<' in driver.page_source
     driver.find_element_by_id('id-submit').click()
     WebDriverWait(driver, 10).until(EC.title_contains('Submit application'))
Esempio n. 23
0
def title_contains(driver, title, timeout=3):
    try:
        w = WebDriverWait(driver, timeout)
        w.until(EC.title_contains(title))
        return True
    except TimeoutException:
        return False
Esempio n. 24
0
 def click_buy(self):
     ''' clicks the buy button on the book modal '''
     self._confirm_modal()
     
     _purchase_button = self._webd_wrap._driver.find_element_by_class_name('l-230px').find_element_by_xpath('div/div/span/a')
     self._webd_wrap._driver.execute_script('$(arguments[0]).click()', _purchase_button)
     self._webd_wrap.wait.until(EC.title_contains("Zola"))
 def wait_for_title_contains(self, title, seconds):
     try:
         is_present = WebDriverWait(self.driver, seconds).until(
             EC.title_contains(title))
     except TimeoutException:
         is_present = False
     return is_present
Esempio n. 26
0
def getBofa(*args):
	username = args[0][2]
	password = args[0][3]

	driver = webdriver.Firefox()
	
	driver.get(url)
	wait = lambda msg: WebDriverWait(driver, 10).until(EC.title_contains(msg))

	driver.find_element_by_id("onlineId1").send_keys(username)
	driver.find_element_by_id("passcode1").send_keys(password)
	driver.find_element_by_id("hp-sign-in-btn").click()
	wait("Bank of America")

	if (driver.current_url.find(failedUrl) == -1 and driver.current_url.find(successUrl) != -1):
		driver.quit()
		raise Exception("Your Password or Username were incorrect!")
	wait("Bank of America")

	if (driver.current_url == secureURl):
		raise Exception("Your identity needs to be verified. Please enter your information and try again")

	wait("Accounts Overview")

	balance = driver.find_element_by_xpath("//*[@id=\"Traditional\"]/li[1]/div[1]/div[1]")
	print "Your Checkings Balance is " + balance.text + "."

	driver.find_element_by_name("onh_sign_off").click()
	driver.quit()
Esempio n. 27
0
    def test_chrome(self):
        """Can I get chrome to work via WebDriver?"""

        # Create a new instance of the Chrome driver
        driver = webdriver.Chrome()

        # go to the google home page
        driver.get("http://www.google.com")

        # the page is ajaxy so the title is originally this:
        print driver.title

        # find the element that's name attribute is q (the google search box)
        input_element = driver.find_element_by_name("q")

        # type in the search
        input_element.send_keys("cheese!")

        # submit the form (although google automatically searches now without submitting)
        input_element.submit()

        try:
            # we have to wait for the page to refresh, the last thing that seems
            # to be updated is the title
            WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))

            # You should see "cheese! - Google Search"
            print driver.title

            if driver.title != "cheese! - Google Search":
                self.fail()

        finally:
            driver.quit()
Esempio n. 28
0
	def test_google_search(self):
		# Create a new instance of the Firefox self.driver
		#self.driver = webself.driver.Firefox()

		# go to the google home page
		self.driver.get("http://www.google.com")

		# find the element that's name attribute is q (the google search box)
		inputElement = self.driver.find_element_by_name("q")

		# type in the search
		inputElement.send_keys("cheese!")

		# submit the form (although google automatically searches now without submitting)
		inputElement.submit()

		# the page is ajaxy so the title is originally this:
		print( self.driver.title )

		try:
		    # we have to wait for the page to refresh, the last thing that seems to be updated is the title
		    WebDriverWait(self.driver, 10).until(EC.title_contains("cheese!"))

		    # You should see "cheese! - Google Search"
		    print( self.driver.title )
		    self.assertTrue(  self.driver.title.find(  "cheese!" ) != -1 )

		finally:
		    self.driver.quit()
Esempio n. 29
0
  def bind(self):
    ''' Class [ GoogleSeleniumKlass ] - bind(none) => Access '''
    driver = self.getDriver();
    try:
      driver.get(self.url);
      elem = driver.find_element(
        By.XPATH,
        '//*[@id="lst-ib"]'
      );
      elem.send_keys('python');
      elem.send_keys(self.keys.RETURN);
      self.getWaiting().until(EC.title_contains('- Google'));
    except NoSuchElementException:
      print '\n-+-+-+- NoSuchElementException -+-+-+-\n';
    except TimeoutException:
      print '\n-+-+-+- TimeoutException -+-+-+-\n';
    finally:
      print '\nFin.\n'
      driver.close();

# Sub Import
# from GoogleSelenium import GoogleSeleniumKlass;
## [Test] - GoogleSelenium Klass
# test = GoogleSeleniumKlass(
#   'Google',
#   'https://www.google.co.jp/'
# );
# test.bind();
Esempio n. 30
0
    def wait_until_title_contains(self, phrase):
        """ Wait for title to contain supplied phrase

            :param phrase: phrase contained in title
            :type phrase: str
        """
        self.wait.until(EC.title_contains(phrase))
 def check_element(self, elementname):
     a = EC.title_contains(elementname)
     print("检查页面是否正确:", a)
Esempio n. 32
0
 def check_title_contains(self):
     result = EC.title_contains('სამი გოჭი')
     return result
def step_impl(context, message):
    """ Check the document title for a message """
    # expect(context.driver.title).to_contain(message)
    found = WebDriverWait(context.driver, WAIT_SECONDS).until(
        expected_conditions.title_contains(message))
    expect(found).to_be(True)
Esempio n. 34
0
    def get_hotel(self, driver, to_city, fromdate, todate):
        # 搜素前的页面,获取元素位置,以便访问
        ele_toCity = driver.find_element_by_name('toCity')
        ele_fromDate = driver.find_element_by_id('fromDate')
        ele_toDate = driver.find_element_by_id('toDate')
        ele_search = driver.find_element_by_class_name('search-btn')

        ele_toCity.clear()
        ele_toCity.send_keys(to_city)
        ele_toCity.click()
        ele_fromDate.clear()
        ele_fromDate.send_keys(fromdate)
        ele_toDate.clear()
        ele_toDate.send_keys(todate)
        ele_search.click()

        # 点击搜索之后的页面
        page_num = 0
        while True:
            # 下拉到底部,获取完整的数据
            try:
                WebDriverWait(driver, 10).until(EC.title_contains(to_city))
            except Exception as e:
                print(e)
                if page_num > 5:
                    break

            time.sleep(5)
            try:
                js = 'window.scrollTo(0, document.body.scrollHeight);'
                driver.execute_script(js)
            except Exception as e:
                print(e)

            time.sleep(5)
            # 解析酒店信息,将数据进行清洗和存储
            htm_const = driver.page_source
            soup = BeautifulSoup(htm_const, 'html.parser', from_encoding='utf-8')
            infos = soup.find_all(class_='item_hotel_info')

            # 输出到文件
            f = codecs.open(to_city + fromdate + '.html', 'a', 'utf-8')
            for info in infos:
                f.write(str(page_num) + '--' * 50)
                content = info.get_text().replace(' ', '').replace('\t', '').strip()
                for line in [ln for ln in content.splitlines() if ln.strip()]:
                    f.write(line)
                    f.write('\r\n')
            f.close()

            # 点击下一页,继续重复这一过程
            try:
                next_page = WebDriverWait(driver, 10).until(EC.visibility_of(
                    driver.find_element_by_css_selector('.item.next')))
                next_page.click()
                page_num += 1
                time.sleep(10)
            except Exception as e:
                print(e)
                if page_num > 5:
                    break
from selenium.webdriver.support import expected_conditions as EC

# Create a new instance of the Chrome driver
# Pass the location of your web driver to executable_path
# parameter while instantiating Chrome Driver
driver = webdriver.Chrome(executable_path="C:\\Selenium\\chromedriver.exe")
#Uncomment next line if you have a slow internet connection
#WebDriverWait(driver, 10)
# go to the BPBOnline home page
driver.get("https://bpbonline.com")
# the page Uses AJAX - lets check the title
print(driver.title)
# find the element that's name attribute is Product search
inputElement = driver.find_element_by_id('bc-product-search')
# type in the search term in the search bar
inputElement.send_keys("C")
# submit the search
inputElement.submit()
try:
    # Wait to check for the title to get loaded
    WebDriverWait(driver, 10).until(EC.title_contains("C"))
    # You should see "C in the title Search"
    print(driver.title)
    #Print the Page content in HTML format
    print(driver.page_source)
    #Save the Screen Shot as a file
    driver.get_screenshot_as_file("BPBonline_C_Output.png")
finally:
    #Close the Driver
    driver.quit()
Esempio n. 36
0
def download(user,
             password,
             dir='.',
             nome=None,
             chiusi=False,
             inserimento=False):
    options = webdriver.FirefoxOptions()
    options.headless = True

    profile = webdriver.FirefoxProfile()
    profile.set_preference("profile.default_content_settings.popups", 0)

    driver = webdriver.Firefox(options=options, firefox_profile=profile)

    driver.get("https://work.unimi.it/boDocenti/ListaAppelliEIscritti")

    elem = driver.find_element_by_id("username")
    elem.clear()
    elem.send_keys(user)

    elem = driver.find_element_by_id("password")
    elem.clear()
    elem.send_keys(password)
    elem.send_keys(Keys.RETURN)

    WebDriverWait(driver, 10).until(EC.title_contains("Lista appelli"))
    driver.find_element_by_id('id1d').click()

    good_idxs = []
    for idx, row in enumerate(driver.find_elements_by_tag_name("tr")):
        if (((APERTO in row.text) or
             (inserimento and INSERIMENTO in row.text) or
             (chiusi and CHIUSO in row.text))
                and (nome is None or (nome.lower() in row.text.lower()))):
            good_idxs.append(idx)

    print('\nTrovati {} appelli...\n'.format(len(good_idxs)))

    for idx in good_idxs:
        row = driver.find_elements_by_tag_name("tr")[idx]

        ds = row.find_elements_by_tag_name('td')

        insegnamento = ds[0].text
        data = ds[1].text
        chiusura = ds[2].text
        fase = ds[3].text
        iscritti = ds[4].text
        tipo = ds[5].text
        presidente = ds[6].text

        path = Path(dir) / '{}@{}.tsv'.format(
            insegnamento[:ds[0].text.index('(') - 1].replace(' ', '_'),
            '-'.join(data.split('/')[::-1]))

        print("""Insegnamento:         {}
Data appello:         {}
Data fine iscrizioni: {}
Fase:                 {}
Iscritti:             {}
Tipo:                 {}
Presidente:           {}
Elenco salvato in:    {}
      """.format(insegnamento, data, chiusura, fase, iscritti, tipo,
                 presidente, path))

        row.find_element_by_tag_name('a').click()
        WebDriverWait(driver, 10).until(EC.title_contains("Elenco studenti"))

        try:
            iscr = driver.find_element_by_tag_name('table')
            table2csv(path, iscr)
        except NoSuchElementException:
            pass

        driver.back()

    driver.close()
Esempio n. 37
0
    def test_page_serve_mtv(self):
        """Test the browser page for MTV can be loaded successfully."""
        TITLE_TEXT = "Mountain View - Graph Browser - Data Commons"

        # Load MTV browser page.
        self.driver.get(self.url_ + MTV_URL)

        # Assert 200 HTTP code: successful page load.
        req = urllib.request.Request(self.driver.current_url)
        with urllib.request.urlopen(req) as response:
            self.assertEqual(response.getcode(), 200)

        # Assert 200 HTTP code: successful JS generation.
        req = urllib.request.Request(self.url_ + "/browser.js")
        with urllib.request.urlopen(req) as response:
            self.assertEqual(response.getcode(), 200)

        # Assert page title is correct.
        WebDriverWait(self.driver,
                      self.TIMEOUT_SEC).until(EC.title_contains(TITLE_TEXT))
        self.assertEqual(TITLE_TEXT, self.driver.title)

        # Assert header is correct.
        element_present = EC.presence_of_element_located((By.TAG_NAME, 'h1'))
        WebDriverWait(self.driver, self.TIMEOUT_SEC).until(element_present)
        title = self.driver.find_element_by_xpath('//*[@id="node"]/h1')
        self.assertEqual(title.text, 'About: Mountain View')
        dcid_subtitle = self.driver.find_element_by_xpath(
            '//*[@id="node"]/h2[1]')
        self.assertEqual(dcid_subtitle.text, 'dcid: geoId/0649670')
        typeOf_subtitle = self.driver.find_element_by_xpath(
            '//*[@id="node"]/h2[2]')
        self.assertEqual(typeOf_subtitle.text, 'typeOf: City')

        # Assert properties contains correct dcid and typeOf
        element_present = EC.presence_of_element_located(
            (By.XPATH, '//*[@id="node-content"]/div[1]/div/table'))
        WebDriverWait(self.driver, self.TIMEOUT_SEC).until(element_present)
        table = self.driver.find_element_by_xpath(
            '//*[@id="node-content"]/div[1]/div/table')
        dcid_row = table.find_elements_by_xpath('.//tbody/tr[2]/td')
        self.assertEqual(dcid_row[0].text, 'dcid')
        self.assertEqual(dcid_row[1].text, 'geoId/0649670')
        typeOf_row = table.find_elements_by_xpath('.//tbody/tr[3]/td')
        self.assertEqual(typeOf_row[0].text, 'typeOf')
        self.assertEqual(typeOf_row[1].text, 'City')
        self.assertEqual(typeOf_row[2].text, 'www.wikidata.org')

        # Assert stat var hierarchy loaded
        element_present = EC.presence_of_element_located(
            (By.ID, 'stat-var-hierarchy-section'))
        WebDriverWait(self.driver, self.TIMEOUT_SEC).until(element_present)
        sv_hierarchy_section = self.driver.find_element_by_id(
            'stat-var-hierarchy-section')
        sv_hierarchy_container = sv_hierarchy_section.find_elements_by_xpath(
            '//*[@id="stat-var-hierarchy-section"]/div')
        self.assertTrue(len(sv_hierarchy_container) > 0)

        # Assert in arcs loaded
        element_present = EC.presence_of_element_located(
            (By.XPATH,
             '//*[@id="browser-in-arc-section"]/div[@class="card p-0"]'))
        WebDriverWait(self.driver, self.TIMEOUT_SEC).until(element_present)
        in_arc_section = self.driver.find_element_by_id(
            'browser-in-arc-section')
        in_arc_cards = in_arc_section.find_elements_by_class_name('card')
        self.assertTrue(len(in_arc_cards) > 0)
Esempio n. 38
0
#coding=utf-8
import time
import random
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from PIL import Image
driver=webdriver.Chrome()
driver.get("http://www.5itest.cn/register")
driver.maximize_window()
time.sleep(5)
EC.title_contains("注册")
email_element=driver.find_element_by_id("register_email")
driver.save_screenshot("e:/imooc.png")
code_element=driver.find_element_by_id("getcode_num")
print(code_element.location)
left=code_element.location['x']
top=code_element.location['y']
right=code_element.size['width']+left
height=code_element.size['height']+top
im=Image.open("e:/imooc.png")
img=im.crop((left,top,right,height))
img.save("e:/imooc1.png")
print(img)

# email_name=driver.find_element_by_id("register_email")
# for i in range(6):
#     user_email=''.join(random.sample('1234567890abcdefg',8))
#     print(user_email)
    # Sign in.
    login_field = driver.find_element_by_name("identifier")
    login_field.send_keys(login["username"])
    login_field.send_keys(Keys.ENTER)

    password_field_name = "password"
    WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.NAME, password_field_name)))

    password_field = driver.find_element_by_name(password_field_name)
    password_field.send_keys(login["password"])
    password_field.send_keys(Keys.ENTER)

    try:
        WebDriverWait(driver, 10).until(EC.title_contains(login["username"]))
        break
    except TimeoutException:
        print("Timed out. Attempting to sign in again.")

# Compose the email.
# Use a keyboard shortcut for Compose.
root = driver.find_element_by_tag_name("html")
root.send_keys("c")

# Wait for the new message window.
to_field_name = "to"
WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.NAME, to_field_name)))

to_field = driver.find_element_by_name(to_field_name)
Esempio n. 40
0
    commits = base_info[0] + " commits\n"
    branches = base_info[1] + " branch(es)\n"
    releases = base_info[2] + " releases\n"
    contributors = base_info[3] + " contributors\n"
    header = "\nBase info:\n"

    print(header + commits + branches + releases + contributors)
    report_file.write(header + commits + branches + releases + contributors)

except Exception as e:
    print(e)
    print("No elements found")

# Inspect files in /src/
browser.find_element_by_link_text("src").click()
element = WebDriverWait(browser, 10).until(EC.title_contains("src"))
try:
    files = browser.find_elements_by_css_selector(
        "span > a[class=js-navigation-open]")
    files = fix_list(files)
    comments = browser.find_elements_by_css_selector("span > a[class=message]")
    comments = fix_list(comments)
    age = browser.find_elements_by_class_name("age")
    age = fix_list(age)
    col_widths = []
    col_widths.append(len(max(files, key=len)) + 2)
    col_widths.append(len(max(comments, key=len)) + 2)
    col_widths.append(len(max(age, key=len)) + 2)

    header = "\nFiles in /src/"
    print(header)
 def title_contains_demo(self):
     title = WebDriverWait(self.driver,
                           10).until(EC.title_contains("PChome"))
     print(title)  # True
Esempio n. 42
0
                              '信用减值损失', '净资本', '净资本增长率', '净资产', '风险覆盖率'))
code_list = [
    '600999', '000166', '601995', '601555', '601901', '601162', '600958',
    '002939', '601990', '002797', '600909', '601236', '601377', '601456',
    '601066', '600837', '601211', '601688', '600030', '601696', '000686',
    '601375', '601788', '600109', '002500', '002673', '002945', '000783',
    '002926', '002736', '601878', '600369', '000728', '601198', '601108',
    '000776', '601099', '000712', '601881', '300059', '600918', '000750'
]
#code_list=['600030','601788','002500']
nb_text = '2020-12-31'
for code in code_list:
    s = {}
    #http://basic.10jqka.com.cn/601099/finance.html#finance
    browser.get('http://basic.10jqka.com.cn/' + code + '/finance.html#finance')
    WebDriverWait(browser, 60 * 10, 0.5).until(EC.title_contains("同花顺金融服务网"))
    sleep(2)
    nb_date(nb_text)
    s['证券代码'] = code
    try:
        s['公司名称'] = browser.find_element_by_xpath(
            "//div[@class='code fl']/div").text
        s['时间'] = nb_text
        if nb_num is not None:
            # 6------------------------------------------------------------
            # 杜邦分析结构图
            browser.execute_script(
                "var q=document.documentElement.scrollTop=10000")
            (s['总资产'], s['资产增长率']) = zb_main('资产总额')
            (s['总负债'], var7) = zb_main('负债总额')
            (s['营业收入'], s['营收增长率']) = zb_main('营业总收入')
Esempio n. 43
0
 def title_contains(self,text):
     '''判断title,返回布尔值'''
     return  WebDriverWait(self.driver, 10).until(EC.title_contains(text))
Esempio n. 44
0
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("--hide-scrollbars")
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=options)
driver.set_window_size(1280, 1080)
wait = WebDriverWait(driver, 10)

driver.get(
    'https://twitter.com/login?redirect_after_login=https%3A%2F%2Fcards-dev.twitter.com%2Fvalidator'
)

wait.until(expected_conditions.title_contains('Twitter'))

driver.find_element_by_css_selector(
    'input[name="session[username_or_email]"]').send_keys(USERNAME)
driver.find_element_by_css_selector(
    'input[name="session[password]"]').send_keys(PASSWORD)
driver.find_element_by_css_selector('div[role]').click()

wait.until(expected_conditions.title_contains('Card Validator'))

url_input = driver.find_element_by_css_selector('input[name="url"]')
submit_button = driver.find_element_by_css_selector('input[type="submit"]')


def twitter_card_validate(url):
    url_input.clear()
Esempio n. 45
0
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()

driver.get("http://www.5itest.cn/register?goto=/")
end_height = driver.execute_script('return document.body.scrollHeight')
while True:
    driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
    time.sleep(random.random() * 10)
    new_height = driver.execute_script('return document.body.scrollHeight')
    print(end_height, new_height)
    if new_height == end_height:
        break
    end_height = new_height

time.sleep(1)
print(EC.title_contains("注册"))

#element = driver.find_elements_by_class_name("controls")[1]
locator = (By.CLASS_NAME, "controls")
WebDriverWait(driver, 1).until(EC.visibility_of_element_located(locator))
for i in range(5):
    user_email = ''.join(random.sample("123456789abcdefg", 5)) + "@163.com"

driver.save_screenshot("1.png")
code_element = driver.find_element_by_id("getcode_num")
left = code_element.location['x']
top = code_element.location['y']
right = code_element.size['width'] + left
height = code_element.size['height'] + top
im = Image.open("1.png")
#im.crop((left,top,right,height))
 def test_03(self):
     result3 = EC.title_contains("15239687008")(self.driver)
     self.assertTrue(result3)
Esempio n. 47
0
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('http://imooc.com')
title_name = driver.title
if '慕课网' in title_name:
    print('网页打开正确')
else:
    print('网页打开失败')
title = driver.title
title_a = EC.title_is('慕课网')
print(title_a(driver))
title_b = EC.title_contains('慕课网')
print(title_b(driver))
driver.close()
'''
print(EC.title_is('慕课网'))
print(EC.title_contains('慕课网'))
'''
Esempio n. 48
0
 def wait_page_loaded(self, title_text):
     """ wait page is loaded to continue test """
     wait = WebDriverWait(self.selenium, 10)
     wait.until(EC.title_contains(title_text))
Esempio n. 49
0
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

# Create a new instance of the Firefox driver
driver = webdriver.Chrome()

# go to the google home page
driver.get("http://www.google.com")

# the page is ajaxy so the title is originally this:
print driver.title

# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")

# type in the search
inputElement.send_keys("cheese!")

# submit the form (although google automatically searches now without submitting)
inputElement.submit()

try:
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title
    WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))

    # You should see "cheese! - Google Search"
    print driver.title

finally:
    driver.quit()
def googleBuilderReviews(index):
    print builderName[index]
    url = "https://www.google.co.in/"  #open google to search
    driver = webdriver.Firefox()  #openeing new instance of firefox.
    driver.maximize_window()  #maximize the size of window

    #driver = webdriver.Chrome('/usr/PriyanshuSinha/B.TECH(2014-2018)/V-Sem/MINOR/crawler/chromedriver') #opening instance of chrome browser
    driver.get(url)
    action_chain = ActionChains(
        driver)  #making action chains to perform actions in succession
    googleSearchResultWindow = driver.current_window_handle  #saving the current state of tab
    #print driver.title
    getSearchBox = driver.find_element(
        By.NAME, "q")  #'q' is name of input type search box
    searchQuery = builderName[index] + 'Builders Reviews'
    #print searchQuery
    getSearchBox.send_keys(searchQuery)
    getSearchBox.submit()
    WebDriverWait(driver, 30).until(ec.title_contains(searchQuery))
    #print driver.title
    divLinkClass = driver.find_element_by_css_selector('div.g')
    getLink = divLinkClass.find_element_by_tag_name("a")
    #print divLinkClass.text
    Link = getLink.get_attribute("href")
    action_chain.context_click(getLink).send_keys(Keys.ARROW_DOWN).send_keys(
        Keys.ENTER).send_keys(Keys.CONTROL + Keys.TAB)
    action_chain.perform()
    driver.switch_to_window(googleSearchResultWindow)
    totalReviews = getRatingReviewCount(driver.page_source, builderName[index])
    if (totalReviews == False):
        driver.quit()
    #totalCount = int(totalReviews)
    else:
        count = 0
        proceed = True
        while proceed:
            try:
                #selectDiv = driver.find_elements_by_tag_name('li')
                for div in driver.find_elements_by_tag_name('li'):
                    get_li = div.find_elements_by_class_name('reviewdetails')
                    for li in get_li:
                        if (li.find_element_by_link_text(
                                'Read complete review')):
                            getMoreReviewLink = li.find_element_by_link_text(
                                'Read complete review')
                            get_link = getMoreReviewLink.get_attribute("href")
                            print get_link
                            try:
                                getMoreReviewLink.click()
                                sleep(8)
                                driver.find_element_by_tag_name(
                                    'body').send_keys(Keys.CONTROL + Keys.TAB)
                                driver.switch_to_window(
                                    googleSearchResultWindow)
                                print driver.title
                                count += 1
                                print count
                                retVal = extractReviewBS(driver.page_source)
                                sleep(10)
                            except:
                                pass
                        else:
                            retVal = extractReview(driver.page_source)
                        if retVal:
                            sleep(5)
                            driver.find_element_by_tag_name('body').send_keys(
                                Keys.CONTROL + 'w')
                        driver.switch_to_window(googleSearchResultWindow)
                #driver.switch_to_window(googleSearchResultWindow)
                paging = driver.find_element_by_class_name('paging')
                next_page = paging.find_element_by_tag_name('span')
                linkNextPage = next_page.find_element_by_class_name('Next')
                nextLink = linkNextPage.get_attribute("href")
                print paging.text
                print next_page.text
                print nextLink
                driver.execute_script("window.open('" + nextLink +
                                      "', '_parent');")
            except:
                print 'Finished All Pages'
                proceed = False
        print 'Out of While Loop'
        driver.quit()
        print 'Dumping Data to File'
        writeInFile(builderName[index])
        review_data.clear()
Esempio n. 51
0
def obtain_company_files(ccvm, options, doc_type, from_date=None):
    """
    This function is responsible for get the relation of files to be
    processed for the company and start its download

    This function is being throttle allowing 20 downloads per minute

    :param driver: the panthomjs or chromium driver with the current page
               loaded. We use the driver to navigate through the
               listing if needed
    """

    # We need to setup the Cassandra Object Mapper to work on multiprocessing
    # If we do not do that, the processes will be blocked when interacting
    # with the object mapper module
    setup_cassandra_object_mapper()

    files = []
    driver = None

    try:
        driver = CrawlersRegistry().get_crawler(
            BOVESPA_CRAWLER).get_web_driver(**options)

        encoded_args = urlencode({
            'CCVM': ccvm,
            'TipoDoc': 'C',
            'QtLinks': "1000"
        })
        url = COMPANY_DOCUMENTS_URL.format(encoded_args)
        _logger.debug("Crawling url: {}".format(url))

        # Let's navigate to the url and wait until the reload is being done
        # We control that the page is loaded looking for an element with
        # id = "AIR" in the page
        driver.get(url)
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.NAME, 'AIR')))
        except TimeoutException:
            WebDriverWait(driver, 10).until(EC.title_contains("CBLCNET -"))
            _logger.warning(
                "There is no documents page for company {ccvm} "
                "and {doc_type}. Showing 'Error de Aplicacao'".format(
                    ccvm=ccvm, doc_type=doc_type))
            return files

        # Once the page is ready, we can select the doc_type from the list
        # of documentation available and navigate to the results page
        # Select ITR files and Click
        element = driver.find_element_by_link_text(doc_type)
        element.click()

        # Wait until the page is loaded
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.XPATH, "//form[@name='AIR']/table/*")))
        except TimeoutException:
            WebDriverWait(driver, 10).until(EC.title_contains("CBLCNET -"))
            _logger.warning(
                "There is no documents page for company {ccvm} "
                "and {doc_type}. Showing 'Error de Aplicacao'".format(
                    ccvm=ccvm, doc_type=doc_type))
            return files

        bs = BeautifulSoup(driver.page_source, "html.parser")

        # We extract the references to all the ENET files
        # The ENET files are ZIP files that contains textual document that
        # we can parse and extract information from them
        files = extract_ENET_files_from_page(ccvm, driver, bs, doc_type,
                                             from_date)

        return files
    except NoSuchElementException as ex:
        _logger.warning(
            "The company {ccvm} do not have {doc_type} documents".format(
                ccvm=ccvm, doc_type=doc_type))
        return []
    finally:
        _logger.debug("Finishing to crawl company "
                      "[{ccvm} - {doc_type}] files: [{num_files}]".format(
                          ccvm=ccvm, doc_type=doc_type, num_files=len(files)))
        if driver:
            _logger.debug("Closing the Selenium Driver for company "
                          "[{ccvm} - {doc_type}]".format(ccvm=ccvm,
                                                         doc_type=doc_type))
            driver.quit()
Esempio n. 52
0
 def wait_title(self, title):
     WebDriverWait(self, 5).until(EC.title_contains(title))
Esempio n. 53
0
    executable_path="C:\Drivers\chromedriver_win32\chromedriver.exe")

driver.get(
    "https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"
)  # open url in browser

driver.maximize_window()
print(driver.title)  # get the title of the page

wait = WebDriverWait(driver, 60)  # explicit wait object
driver.find_element_by_name('identifier').send_keys("<your_email_here>" +
                                                    Keys.ENTER)
ele = wait.until(EC.element_to_be_clickable((By.NAME, 'password')))
ele.send_keys("<your_email_password_here>" + Keys.ENTER)

ele = wait.until(EC.title_contains('Inbox'))
try:
    driver.find_element_by_xpath("//*[@id=':l5']/div/div").click()
except NoSuchElementException:
    driver.find_element_by_xpath("//*[@id=':le']/div/div").click()

ele = wait.until(EC.element_to_be_clickable((By.NAME, 'to')))
rec_email = input("Enter email of the receiver..")
ele.send_keys(rec_email)

ele = driver.find_element_by_name('subjectbox')
ele.send_keys("Test mail" + Keys.TAB +
              "This is a system generated mail. Please do not reply." +
              Keys.CONTROL + Keys.ENTER)

driver.close()
Esempio n. 54
0
 def wait_for_title_update(self, term):
     self.wait.until(EC.title_contains(term))
     return self
Esempio n. 55
0
 def is_title_contains(self, title, timeout=10):
     result = WebDriverWait(self.driver, timeout,
                            1).until(EC.title_contains(title))
     return result
Esempio n. 56
0
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from seleniumtester import SeleniumTester

st = SeleniumTester('Nagios')

username = st.get_variable('NAGIOS_USER')
password = st.get_variable('NAGIOS_PASSWORD')
nagios_uri = st.get_variable('NAGIOS_URI')
nagios_url = 'http://{0}:{1}@{2}'.format(username, password, nagios_uri)

try:
    st.logger.info('Attempting to connect to Nagios')
    st.browser.get(nagios_url)
    el = WebDriverWait(st.browser, 15).until(EC.title_contains('Nagios'))
    st.logger.info('Connected to Nagios')
except TimeoutException:
    st.logger.critical('Timed out waiting for Nagios')
    st.browser.quit()
    sys.exit(1)

try:
    st.logger.info('Switching Focus to Navigation side frame')
    sideFrame = st.browser.switch_to.frame('side')
except NoSuchElementException:
    st.logger.error('Failed selecting side frame')
    st.browser.quit()
    sys.exit(1)

try:
Esempio n. 57
0
def should_load_the_webpage(context):
    WebDriverWait(context.browser, 10).until(EC.title_contains(u'Comprar en '))
    assert context.failed is False
Esempio n. 58
0
webdriver.get(
    "https://wrem.sis.yorku.ca/Apps/WebObjects/REM.woa/wa/DirectAction/rem")
webdriver.get_screenshot_as_file("addCourse.png")
login = webdriver.find_element_by_name("loginform")
userElement = login.find_element_by_id("mli")
passElement = login.find_element_by_id("password")
loginButtonElement = webdriver.find_element_by_name("dologin")
#This is where you input your yorku passport username
userElement.send_keys("USER")
#This iswhere you input your yorku passport password
passElement.send_keys("PASS")

loginButtonElement.click()

webdriver.get_screenshot_as_file("confirmation.png")
WebDriverWait(webdriver, 10).until(EC.title_contains("REM - Main"))
webdriver.get_screenshot_as_file("enrollmentPage.png")
selection = webdriver.find_element_by_tag_name("select")
selection.click()
allOptions = selection.find_elements_by_tag_name("option")
for option in allOptions:
    print "Option is:" + option.get_attribute("value")
    # at this time option 1 = enroll in Fall2019/Winter2020
    # the options might change over time
    if (option.get_attribute("value") == '1'):
        option.click()

webdriver.get_screenshot_as_file("optionSelected.png")
webdriver.quit()
Esempio n. 59
0
    def start_upload(self, upload_type):
        driver = self.driver
        if 'people' in upload_type:
            driver.get(self.BASE_URL + '/admin/upload/entities/mapping')
        if 'info' in upload_type:
            driver.get(self.BASE_URL + '/admin/upload/fields')
        print("Starting %s upload: %s" % (upload_type, self.CAMPAIGN_NAME))
        WebDriverWait(driver, 20).until(EC.title_contains("Upload"))
        # Upload file
        driver.find_element_by_css_selector('input[type="file"]').send_keys(self.UPLOAD_FILE)
        # Select campaign
        campaign_select = driver.find_element(By.CSS_SELECTOR, ".mapping app-campaign-select2")
        campaign_select.click()
        campaign_select.find_element(By.TAG_NAME, "input").send_keys(self.CAMPAIGN_NAME)
        time.sleep(1)
        for item in campaign_select.find_elements(By.TAG_NAME, "app-list-item"):
            if item.text == self.CAMPAIGN_NAME:
                item.click()
                break
        # Select People entity type
        entity_select = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//mat-select[@placeholder='Entity Type']")))
        entity_select.send_keys('People')

        # driver.find_element(
        #     By.XPATH, "//mat-select[@data-test-id='campaignUploadSelect']").send_keys(self.CAMPAIGN_NAME)
        # Select ID for matching
        ID_SOURCE = (By.XPATH, "//mat-select[@placeholder='Id to use for matching']")
        ID_DEST = (By.XPATH, "//mat-select[@placeholder='Upload Column'][@aria-disabled='false']")
        FIELD_SOURCE = (By.CLASS_NAME, 'mapping__col--source')
        WebDriverWait(driver, 5).until(EC.element_to_be_clickable(ID_SOURCE))
        driver.find_element(*ID_SOURCE).send_keys(self.FIELD_MAP['id']['ab_type'])
        # Map Fields
        print("Mapping %s fields: %s" % (upload_type, self.CAMPAIGN_NAME))
        if 'people' in upload_type:
            col_name = (By.CSS_SELECTOR, '.mapping__col--source input')
            fields = driver.find_elements_by_class_name('mapping')
            for field in fields[:-2]:  # last two are notification and button
                if field.find_elements(*col_name):
                    column = field.find_element(*col_name).get_attribute('value')
                    if column == self.FIELD_MAP['id']['column']:
                        map_to = self.FIELD_MAP['id']['ab_type']
                    else:
                        map_to = self.FIELD_MAP[upload_type].get(column)
                    if map_to:
                        field.find_element(By.TAG_NAME, 'mat-select').send_keys(map_to)
            time.sleep(3)
            driver.find_element(By.XPATH, "//button[contains(text(), 'Process Upload')]").click()

        if 'info' in upload_type:
            WebDriverWait(driver, 5).until(EC.presence_of_element_located(ID_DEST))
            driver.find_element(*ID_DEST).send_keys(self.FIELD_MAP['id']['column'])
            WebDriverWait(driver, 5).until(lambda d: len(d.find_elements(*FIELD_SOURCE)) > 1)
            fields = driver.find_elements(*FIELD_SOURCE)
            for field in fields[1:]:
                col_name = field.find_element(
                    By.TAG_NAME, 'input').get_attribute('value')
                if col_name in self.FIELD_MAP[upload_type]:
                    field_info = self.FIELD_MAP[upload_type][col_name]
                    dest = field.find_element(By.XPATH, './following-sibling::*[2]')
                    dest.find_element(By.TAG_NAME, 'button').click()
                    # Select field
                    driver.find_element(By.XPATH, '//app-field-search-inline//input').send_keys(field_info['name'])
                    try:
                        driver.find_element(By.XPATH, '//app-field-search-inline//mat-list-option').click()
                    except NoSuchElementException:
                        # Clear dialog
                        driver.find_element(By.TAG_NAME, 'body').click()
                    if field_info['type'] == 'notes':
                        driver.find_element(By.XPATH, '//mat-dialog-container//mat-select').send_keys(field_info['note_col'])
                        driver.find_element(By.XPATH, "//mat-dialog-container//button[text()='Apply Field Mapping']").click()
                        time.sleep(1)
            driver.find_element(By.XPATH, '//button[contains(text(),"Next Step")]').click()
            WebDriverWait(driver, 10).until(EC.title_contains('Map to responses'))
            time.sleep(2)
            driver.find_element(By.XPATH, '//button[contains(text(),"Next Step")]').click()
            WebDriverWait(driver, 10).until(EC.title_contains('Create Responses'))
            CONF_LOCATOR = (By.XPATH, '//app-upload-fields-step3-page//button')
            checkboxes = driver.find_elements(
                By.XPATH, '//app-upload-fields-step3-page//mat-checkbox//label')
            if len(checkboxes) > 0:
                print('Creating tags: %s' % self.CAMPAIGN_NAME)
                for checkbox in checkboxes:
                    checkbox.click()
                driver.find_element(*CONF_LOCATOR).click()
                WebDriverWait(driver, 200).until(EC.element_to_be_clickable(CONF_LOCATOR))
            time.sleep(3)
            driver.find_element(*CONF_LOCATOR).click()

        # Make sure the "processing" button worked
        WebDriverWait(driver, 30).until(EC.url_changes(driver.current_url))
        print('---Fields mapped for %s: %s---' % (upload_type, self.CAMPAIGN_NAME))
Esempio n. 60
0
# EC是 expected_conditions的别名
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
res = EC.title_is('百度一下,你就知道')(driver)
assert res == True
res = EC.title_contains('百度一')(driver)
print(res)