How do I logon to webpage using python ansdselenium? - python

driver.find_element_by_id('username').send_keys('945412')
print 'username entered'
driver.find_element_by_name('password').send_keys('mns347')
print 'password entered'
driver.find_element_by_name("submit").click()
print 'submit'
but it is throwing error
Traceback (most recent call last):
File "C:\Users\SS\Desktop\python-mp\sele_sample.py", line 17, in <module>
driver.find_element_by_id('username').send_keys('945412')
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"username"}
(Session info: chrome=70.0.3538.102)
(Driver info: chromedriver=2.44.609538 (b655c5a60b0b544917107a59d4153d4bf78e1b90),platform=Windows NT 6.3.9600 x86_64)

You can add explicit wait to wait for element to be loaded.
username= WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.ID, "username"))
)
username.send_keys('945412')

I can't see any mistake in your code. But according to your error message, there is no field with the id username.
Please make sure that there really is a field with the id username on your website.
As an example, githubs username field is defined as follows
<input name="login" id="login_field" class="form-control input-block" tabindex="1" autocapitalize="off" autocorrect="off" autofocus="autofocus" type="text">
In this case you would have to adapt your code to this. This would look like this
driver.find_element_by_id('login_field').send_keys('945412')
Because the field contains id="login_field"

import the by module and try this instead,
from selenium.webdriver.common.by import By
element = driver.find_element(by=By.ID, value="username")
element.send_keys('945412')
use wait like below, if the above code doesn't work username= WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.ID, "username"))
);
username.send_keys('945412.')

You need to install chromedriver and chrome. You can change these settings for other browsers if you want. This work fine for me.
from selenium import webdriver
browser = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")
browser.get('<login_url>')
username = browser.find_element_by_name("<username_name_tag>")
password = browser.find_element_by_name("<password_name_tag>")
username.send_keys("<username>")
password.send_keys("<password>")
browser.find_element_by_id("<login_button_id>").click()

Related

Selenium find_element_by_xpath

I am trying to buy a product, so it needs to be added to the cart which is working but when I am trying to click on the checkout button I get an error.
open chromedriver
driver = webdriver.Chrome(r'C:\Users\x\OneDrive\Desktop\chromedriver.exe')
driver.get('https://feature.com/products/billionaire-boys-club-kids-bb-copilot-polo-black')
driver.find_element_by_xpath('//div[#data-value="3T"]').click()
driver.find_element_by_xpath('//button[#class="AddToCart default-btn"]').click()
Until this part it is working, but trying to check out it isn't working.
driver.find_element_by_xpath('//button[#name="checkout"]').click()
<button type="submit" class="btn--secondary btn--full cart__checkout"
name="checkout" value="Check Out →">
Check Out
</button>
I'm getting this error:
File "C:\Users\x\OneDrive\Desktop\Sp\Snx.py", line 35, in <module>
driver.find_element_by_xpath('//button[#name="checkout"]').click()
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[#name="checkout"]"}
(Session info: chrome=74.0.3729.131)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729#{#29}),platform=Windows NT 10.0.17134 x86_64)
It's because you need wait to "checkout" button appears before selenium search and click it
import time
from selenium import webdriver
driver = webdriver.Chrome(r'C:\Users\x\OneDrive\Desktop\chromedriver.exe')
driver.get('https://feature.com/products/billionaire-boys-club-kids-bb-copilot-polo-black')
driver.find_element_by_xpath('//div[#data-value="3T"]').click()
driver.find_element_by_xpath('//button[#class="AddToCart default-btn"]').click()
time.sleep(2)
cart_container = driver.find_element_by_id('CartContainer')
cart_container.find_element_by_name('checkout').click()
This example I used time.sleep(secs), where there's no guarantee that the element was already show up.
If you want improve, there's a class called WebDriverWait, more information here: Wait until page is loaded with Selenium WebDriver for Python

Automated login

I'm trying to run python selenium and automate the login process.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime, date
currentDate = ("{:%Y%m%d}".format(datetime.now()))
usernameStr = 'email'
passwordStr = 'passoword'
browser = webdriver.Chrome()
browser.get('http://website.com/en/entry?' + 'date=' + currentDate)
delay = 3
loginButton = browser.find_element_by_xpath('//*[#id="global-header"]/div[2]/ul/li[2]/a')
loginButton.click()
delay = 3
Username = browser.find_element_by_name('Username or Email Address')
Username.send_keys(usernameStr)
password = browser.find_element_by_name('password')
password.send_keys(passwordStr)
nextButton = browser.find_element_by_class_name('vm.submitLogin()')
nextButton.click()
Here is the html I'm trying to access
<span class="input-wrapper">
<input type="email" placeholder="Username or Email Address"
autocapitalize="none" autocomplete="on" autocorrect="off" spellcheck="false"
ng-model="vm.username" ng-pattern="/^[^<">]*$/"
ng-required="true" did-disable-validate="
"ng-focus="vm.resetUsername()"
class="ng-pristine ng-invalid ng-invalid-required ng-valid-pattern
ng-touched" tabindex="0"
required="required" aria-required="true" aria-invalid="true"></span>
I've tried to access the html by name, css selector, xpath, but nothing seems to work. It's a login banner and not a standard html page so idk if that makes a difference or not.
oh ya here is there error I get
Traceback (most recent call last):
File "/Users/aj/Desktop/streakscraper/login.py", line 20, in <module>
Username = browser.find_element_by_name('Username or Email Address')
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 378, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 784, in find_element
'value': value})['value']
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 249, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"name","selector":"Username or Email Address"}
(Session info: chrome=57.0.2987.133)
(Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.4 x86_64)
You should switch to the correct iframe, then try to match the html:
To change to a different iframe use:
driver.switch_to.frame(driver.find_element_by_name("iframe_name"))
or simply:
driver.switch_to.frame("iframe_name")
You can also access it by index:
driver.switch_to.frame(0) # 1, 2, etc.. if you have multiple iframes
To switch back to the main content use:
driver.switch_to.default_content()

Element not visible when use python and selenium to conduct auto-logging in outlook.com

I wanna write a script to automatically log in outlook mail with python and selenium. But after mail address identification, the script always stops at the password part. But these two parts are totally same at all! I must be wrong somewhere. Sincerely ask for help.
My code is like following:
browser.get('https://login.live.com/login.srf?&wreply=https%3a%2f%2foutlook.live.com%2fowa%2f%3fnlp%3d1%26realm%3dlogin.live.com')
username = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.XPATH, "//input[#id='i0116']")))
username.clear()
username.send_keys(usernameStr)
nextButton = browser.find_element_by_id('idSIButton9')
nextButton.click()
password = WebDriverWait(browser, 50).until(
EC.presence_of_element_located((By.XPATH, "//input[#id='i0118']")))
password.clear()
password.send_keys(passwordStr)
signinButton = browser.find_element_by_id('idSIButton9')
signinButton .click()
the errors:
Traceback (most recent call last):
File "test.py", line 29, in <module>
browser.find_element_by_id('i0118').click()
File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdrive
r\remote\webelement.py", line 77, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdrive
r\remote\webelement.py", line 494, in _execute
return self._parent.execute(command, params)
File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdrive
r\remote\webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium-3.0.2-py2.7.egg\selenium\webdrive
r\remote\errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not visi
ble
(Session info: chrome=55.0.2883.87)
(Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cf
d9),platform=Windows NT 6.1.7601 SP1 x86)
You should try to replace presence_of_element_located condition with visibility_of_element_located:
password = WebDriverWait(browser, 50).until(
EC.visibility_of_element_located((By.XPATH, "//input[#id='i0118']")))
password.clear()

selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with

Currently working to use Python to login with Twitter.
Twitter's login page is here. The source code where the Username and Password input fields are:
<div class="LoginForm-input LoginForm-username">
<input
type="text"
class="text-input email-input js-signin-email"
name="session[username_or_email]"
autocomplete="username"
placeholder="Phone, email or username"
/>
</div>
<div class="LoginForm-input LoginForm-password">
<input type="password" class="text-input" name="session[password]"
placeholder="Password" autocomplete="current-password">
</div>
So when I write my code in Python utilizing the Selenium module:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("https://twitter.com/login")
elem = driver.find_element_by_name("session[username_or_email]")
elem.clear()
elem.send_keys(username)
elem = driver.find_element_by_name("session[password]")
elem.clear()
elem.send_keys(password)
elem.send_keys(Keys.RETURN)
sleep(delay)
The error that is returned:
selenium.common.exceptions.ElementNotVisibleException: Message: Element
is not currently visible and so may not be
interacted with
Any help? Thanks! I have read of the responses of other similar questions, but have not helped much.
Edit:
Full error message:
Traceback (most recent call last):
File "main.py", line 154, in <module>
main()
File "main.py", line 143, in main
twitterBruteforce(username, wordlist, delay)
File "src/twitterLib.py", line 27, in twitterBruteforce
elem.clear()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 88, in clear
self._execute(Command.CLEAR_ELEMENT)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 457, in _execute
return self._parent.execute(command, params)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 233, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
Stacktrace:
at fxdriver.preconditions.visible (file:///tmp/tmpurkUhr/extensions/fxdriver#googlecode.com/components/command-processor.js:10092)
at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpurkUhr/extensions/fxdriver#googlecode.com/components/command-processor.js:12644)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpurkUhr/extensions/fxdriver#googlecode.com/components/command-processor.js:12661)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpurkUhr/extensions/fxdriver#googlecode.com/components/command-processor.js:12666)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpurkUhr/extensions/fxdriver#googlecode.com/components/command-processor.js:12608)
You should try using WebDriverWait to wait until element visible before interaction to the element as below :-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
user = wait.until(EC.visibility_of_element_located((By.NAME, "session[username_or_email]")))
user.clear()
user.send_keys(username)
pass = wait.until(EC.visibility_of_element_located((By.NAME, "session[password]")))
pass.clear()
pass.send_keys(password)
Note :- instead of send_keys(Keys.RETURN) try using click() to the login button element as login_button_element.click() or try using submit() to the form element as form_element.submit() after locating these elements.

Can't properly access element using Python Selenium WebDriver

So I am learning how to use Selenium for web automation - I am trying to write a script that returns my American Express balance to my console. The first step is actually logging on successfully...
It appears that my action for clicking the login button raises an error of not finding the element, even though I can see it when I am on firebug.
This is my code:
from selenium import webdriver
driver = webdriver.Firefox()
baseurl = "https://www.americanexpress.com/canada/"
username = "myusername"
password = "mypassword"
xpaths = { 'usernameField' : "//input[#id='UserID']",
'passwordField' : "//input[#id='Password']",
'submitButton' : "//input[#id='loginButton']"
}
driver.get(baseurl)
driver.find_element_by_xpath(xpaths['usernameField']).clear()
driver.find_element_by_xpath(xpaths['usernameField']).send_keys(username)
driver.find_element_by_xpath(xpaths['passwordField']).clear()
driver.find_element_by_xpath(xpaths['passwordField']).send_keys(password)
driver.find_element_by_xpath(xpaths['submitButton']).click()
This is the console error message I get, where the browser has filled in my login details, but just has not clicked on the login button:
Traceback (most recent call last):
File "get_balance.py", line 29, in <module>
driver.find_element_by_xpath(xpaths['submitButton']).click()
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 232, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 664, in find_element
{'using': by, 'value': value})['value']
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 175, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//input[#id='loginButton']"}
Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/mx/dbnsd72j05zd4k2cls4cvmf00000gn/T/tmpKQDaey/extensions/fxdriver#googlecode.com/components/driver-component.js:10271)
at FirefoxDriver.prototype.findElement (file:///var/folders/mx/dbnsd72j05zd4k2cls4cvmf00000gn/T/tmpKQDaey/extensions/fxdriver#googlecode.com/components/driver-component.js:10280)
at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/mx/dbnsd72j05zd4k2cls4cvmf00000gn/T/tmpKQDaey/extensions/fxdriver#googlecode.com/components/command-processor.js:12274)
at DelayedCommand.prototype.executeInternal_ (file:///var/folders/mx/dbnsd72j05zd4k2cls4cvmf00000gn/T/tmpKQDaey/extensions/fxdriver#googlecode.com/components/command-processor.js:12279)
at DelayedCommand.prototype.execute/< (file:///var/folders/mx/dbnsd72j05zd4k2cls4cvmf00000gn/T/tmpKQDaey/extensions/fxdriver#googlecode.com/components/command-processor.js:12221)
Any thoughts? Any advice/help is much appreciated, thanks!
This is an a element, not an input:
<a tabindex="0" href="#" id="loginButton" title="Login securely">
<span></span>
Log In
</a>
Change your xpath to: //a[#id="loginButton"].
Aside from that, for id attributes there is a find_element_by_id() method:
driver.find_element_by_id("loginButton").click()
Also, if you want to have element locators separated from the actual "action" code, you can configure it the following way (left a single xpath expression for a sake of an example):
from selenium.webdriver.common.by import By
locators = {
'usernameField': (By.ID, "UserID"),
'passwordField': (By.XPATH, "//input[#id='Password']"),
'submitButton': (By.ID, "loginButton")
}
Then, your "action" code would be using find_element():
username = driver.find_element(*locators['usernameField'])
username.clear()
username.send_keys(username)
password = driver.find_element(*locators['passwordField'])
password.clear()
password.send_keys(password)
login_button = driver.find_element(*locators['submitButton'])
login_button.click()

Categories