How to Input value from dropdown in selenium python? - python-3.x

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
EMAILFIELD = (By.ID, "username")
PASSWORDFIELD = (By.ID, "password")
LOGINBUTTON = (By.ID, "Login")
CLICKBUTTON= (By.ID, "thePage:rtForm:createButton")
QUICKFINDSEARCH = (By.ID, "quickFindInput")
browser = webdriver.Chrome(
executable_path=r"C:/Users/RYadav/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Python 3.8/chromedriver.exe")
browser.get('https://fleet.my.salesforce.com/')
# wait for email field and enter email
WebDriverWait(browser, 5).until(EC.element_to_be_clickable(EMAILFIELD)).send_keys("ryadav#gmail.com")
# wait for password field and enter password
WebDriverWait(browser, 5).until(EC.element_to_be_clickable(PASSWORDFIELD)).send_keys("1234zxcvb")
# Click Login - same id?
WebDriverWait(browser, 5).until(EC.element_to_be_clickable(LOGINBUTTON)).click()
#direct new reportfield
browser.get('https://fleet.my.salesforce.com/reportbuilder/reportType.apexp')
#search the Users from dropdown and click button
select = Select(webdriver.find_element_by_id("quickFindInput"))
select.select_by_visible_text("Users")
WebDriverWait(browser, 5).until(EC.element_to_be_clickable(CLICKBUTTON)).click()
Please suggest how to input a value from dropdown to the above code. This code throws Attribute Error.
Traceback (most recent call last):
File "C:/Users/RYadav/PycharmProjects/ElementProject/SalesforceUrl.py", line 30, in <module>
select = Select(webdriver.find_element_by_id("quickFindInput"))
AttributeError: module 'selenium.webdriver' has no attribute 'find_element_by_id'

You were so close. Through out your program you had been using browser as the WebDriver instance. But called through a differnt name webdriver in the line:
select = Select(webdriver.find_element_by_id("quickFindInput"))
You need to change the line as:
select = Select(browser.find_element_by_id("quickFindInput"))

Related

Not able to click on Check box using Selenium Python

I want to click on the check box, but my code is not working. Steps which I want to follow is
Open website
Select Profession e.g:- Dental
License Type e.g :- Dentist
Enter a alphabet with * to get all the records
Click on the check box
Click on search button
Script also ask for image verification for which I am unable to process, any help would be appriciated
home_page = 'https://forms.nh.gov/licenseverification/'
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import csv
from shutil import copyfile
import datetime
import subprocess
import time
import multiprocessing
import sys
import subprocess
current_date=datetime.date.today()
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options
driver = webdriver.Chrome(r"C:\Users\psingh\AppData\Local\Programs\Python\Python38-32\chromedriver.exe")
driver.get(home_page)
select_prof = WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.ID, "t_web_lookup__profession_name")))
Select(select_prof).select_by_value('Dental')
select_lic_type = WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.ID, "t_web_lookup__license_type_name")))
# select profession criteria value
Select(select_lic_type).select_by_value('Dentist')
time.sleep(1)
send = WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.ID, "t_web_lookup__last_name"))
)
send.send_keys('A*')
time.sleep(1)
# click on check box
driver.find_element_by_xpath("/html/body/div[1]").click()
# click search button
driver.find_element_by_id("sch_button").click()
# wait to get the result
time.sleep(1)
The check box which you are trying to click is inside the iframe. First switch to that iframe and then try to click on that checkbox.
Below code works fine in pycharm and windows 10.
driver = webdriver.Chrome(PATH)
url = 'https://forms.nh.gov/licenseverification/'
driver.get(url)
driver.maximize_window()
sleep(5)
select_prof = driver.find_element(By.ID, 't_web_lookup__profession_name')
Select(select_prof).select_by_value('Dental')
select_lic_type = driver.find_element(By.ID, "t_web_lookup__license_type_name")
# select profession criteria value
Select(select_lic_type).select_by_value('Dentist')
sleep(1)
send = driver.find_element(By.ID, "t_web_lookup__last_name")
send.send_keys('A*')
sleep(1)
# click on check box
driver.switch_to.frame(0)
captcha = driver.find_element(By.CSS_SELECTOR, '.recaptcha-checkbox-border')
captcha.click()
# click search button
driver.find_element(By.XPATH, "sch_button").click()
sleep(1)

How to click element using selenium web driver(Python)

I am trying to click an element using selenium chromedriver by the Use of ID of an element to click.
I want to Click Year '2020" from the following webpage: 'https://www.satp.org/datasheet-terrorist-attack/major-incidents/Pakistan'
I tried with the below code.
driver = webdriver.Chrome(executable_path=ChromeDriver_Path, options = options)
driver.get('https://www.satp.org/datasheet-terrorist-attack/major-incidents/Pakistan')
Id = "ctl00_ContentPlaceHolder1_gvMajorIncident_ct123_lbtnYear" ### Id of an Element 2020
wait = WebDriverWait(driver, 20) ##Wait for 20 seconds
element = wait.until(EC.element_to_be_clickable((By.ID, Id)))
driver.execute_script("arguments[0].scrollIntoView();", element)
element.click()
time.sleep(10)
but unfortunately this gives an Error as below:
element = wait.until(EC.element_to_be_clickable((By.ID, Id)))
File "C:\Users\Pavan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
Please anyone help me on this... Thanks;
I don't know if your imports were correct. Also, your code doesn't scroll to the bottom of the page. Use this.
import os
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome(executable_path='driver path')
driver.get('https://www.satp.org/datasheet-terrorist-attack/major-incidents/Pakistan')
driver.maximize_window()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
element = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="ctl00_ContentPlaceHolder1_gvMajorIncident_ctl23_lbtnYear"]')))
element.click()

Error while using Drop-down - Python Selenium

Hi All
Im trying to select a value from drop-down using class_name/xpath
but it's not working. Tried using id but found that the id keeps
changing. Need assistance on this.
This is the dropdown where im trying to select short description
Below is my code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select
import time
username = '*****'
password = '*****'
url = 'https://*****.service-now.com/'
driver = webdriver.Chrome("C:\WebDrivers\chromedriver.exe")
driver.get(url)
driver.switch_to.frame('gsft_main')
driver.maximize_window()
driver.find_element_by_id('user_name').send_keys(username)
driver.find_element_by_id('user_password').send_keys(password)
driver.find_element_by_id('sysverb_login').click()
wait = WebDriverWait(driver, 10)
incident = wait.until(EC.visibility_of_element_located((By.XPATH, '//span[contains(text(),
"Incident")]')))
incident.click()
open = driver.find_element_by_link_text('Open - Unassigned')
open.click()
time.sleep(25)
element = driver.find_element_by_class_name('form-control default-focus-outline')
dropdown.Select(element)
dropdown.select_by_value('short_description')
Below is the element that I copied and got.
Copy Element:
<select id="d5f43fd407945410af12f2ae7c1ed05c_select" class="form-control default-focus-outline" aria-
expanded="false"><option value="zztextsearchyy" selected="SELECTED" role="option">for text</option>
<option value="number" role="option">Number</option><option value="opened_at"
role="option">Opened</option><option value="short_description" role="option">Short
description</option><option value="caller_id" role="option">Caller</option><option value="priority"
role="option">Priority</option><option value="state" role="option">State</option><option
value="category" role="option">Category</option><option value="assignment_group"
role="option">Assignment group</option><option value="assigned_to" role="option">Assigned to</option>
<option value="sys_updated_on" role="option">Updated</option><option value="sys_updated_by"
role="option">Updated by</option></select>
By xpath:
//*[#id="d5f43fd407945410af12f2ae7c1ed05c_select"]
Gives me the below error:
DevTools listening on ws://127.0.0.1:49915/devtools/browser/30b98d3d-0779-4d85-86bc-9af3a24726a2
[7012:3772:0417/104241.308:ERROR:browser_switcher_service.cc(238)] XXX Init()
Traceback (most recent call last):
File "Test.py", line 39, in <module>
element = driver.find_element_by_class_name('form-control default-focus-outline')
File "C:\Python38\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in
find_element_by_class_name
return self.find_element(by=By.CLASS_NAME, value=name)
File "C:\Python38\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in
find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Python38\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Python38\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":"css selector","selector":".form-control default-focus-outline"}
(Session info: chrome=81.0.4044.113)
The above message has two different errors:
1) [7012:3772:0417/104241.308:ERROR:browser_switcher_service.cc(238)]
XXX Init()
2) Unable to locate
element: {"method":"css selector","selector":".form-control default-focus-outline"}
Need help on how do I resolve these issues.
Try with WebDriverWait to resolve your issue. If you are still facing issue then check if your element is present within iframe
wait = WebDriverWait(driver, 30)
wait.until(EC.element_to_be_clickable((By.XPATH, "//select[#id='form-control default-focus-outline']/option[text()='Short description']")))
Note : please add below imports to your solution
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
Working solution :
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
chrome_options = webdriver.ChromeOptions()
options = Options()
chrome_options.add_argument("--disable-notifications")
driver = webdriver.Chrome(executable_path="C:\New folder\chromedriver.exe",chrome_options=chrome_options)
username = '********'
password = '********'
url = 'https://*******.service-now.com/'
driver.get(url)
driver.maximize_window()
wait = WebDriverWait(driver, 20)
iframe = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'gsft_main')))
driver.switch_to.frame(iframe)
wait.until(EC.presence_of_element_located((By.ID, "user_name"))).send_keys(username)
wait.until(EC.presence_of_element_located((By.ID, "user_password"))).send_keys(password)
wait.until(EC.presence_of_element_located((By.ID, "sysverb_login"))).click()
driver.switch_to.default_content()
wait.until(EC.element_to_be_clickable((By.XPATH, "//input[#id='filter']"))).send_keys("Incident")
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[#class='sn-widget-list-title ng-binding'][contains(text(),'Open - Unassigned')]"))).click()
iframe = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, 'gsft_main')))
driver.switch_to.frame(iframe)
print wait.until(EC.element_to_be_clickable((By.XPATH, "//h2[contains(#class,'navbar-title list_title')]"))).text
element=wait.until(EC.element_to_be_clickable((By.XPATH, "//span[#class='input-group-addon input-group-select']//select")))
element=wait.until(EC.presence_of_element_located((By.XPATH, "//span[#class='input-group-addon input-group-select']//select")))
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("value"))
option.click()
select = Select(element)
select.select_by_visible_text("Short description")

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable when clicking on an element using Selenium Python

I understand this question has been asked but I need some solution for this error:
Traceback (most recent call last):
File "goeventz_automation.py", line 405, in <module>
if login(driver) is not None:
File "goeventz_automation.py", line 149, in login
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[#track-element='header-login']"))).click()
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/support/wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
This is the code where its getting error:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import TimeoutException
import urllib.request as request
import urllib.error as error
from PIL import Image
from selenium.webdriver.chrome.options import Options
import datetime as dt
import time
from common_file import *
from login_credentials import *
def login(driver):
global _email, _password
if waiter(driver, "//a[#track-element='header-login']") is not None:
#login = driver.find_element_by_xpath("//a[#track-element='header-login']")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[#track-element='header-login']"))).click()
#login.click()
if waiter(driver,"//input[#id='user_email']") is not None:
email = driver.find_element_by_xpath("//input[#id='user_email']")
password = driver.find_element_by_xpath("//input[#id='password']")
email.send_keys(_email)
password.send_keys(_password)
driver.find_element_by_xpath("//button[#track-element='click-for-login']").click()
return driver
else:
print("There was an error in selecting the email input field. It may be the page has not loaded properly.")
return None
else:
print("There was an error in selecting the header-login attribute on the page.")
return None
if __name__ == '__main__':
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('/usr/bin/chromium/chromedriver',chrome_options=chrome_options)
#d.get('https://www.google.nl/')
#driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.goeventz.com/')
if login(driver) is not None:
print(create_event(driver))
I think there is some problem with Keys.ENTER, but I don't know how to solve this. I have tried every possible solution.............
This error message...
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
...implies that the desired element was not interactable when you tried to invoke click() on it.
A couple of facts:
When you initialize the Chrome browser always in maximized mode.
You can disable-extensions.
You need to disable-infobars as well.
I have used the same xpath which you have constructed and you can use the following solution:
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument("start-maximized");
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.goeventz.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[#track-element='header-login']"))).click()
Browser Snapshot:
copy full xpath instead of copying only xpath. It will work
Instead of using login.send_keys(Keys.ENTER) you should use selenium click() method which would work fine for you.
You can check first if the element is clickable first and then you can click on it.
Like:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[#track-element='header-login']"))).click()
Overview
It seems like you're having an XPATH problem finding the "Submit" button or your Submit button is not clickable, or your Submit button has some client side events attached to it (javascript/etc) that are required in order to effectively submit the page.
Calling the pw.submit() method in most cases should get rid of the need to wait for the submit button to become clickable and avoid any issues in locating the button in most cases. On many other websites, some of the necessary back-end processes are primed by client-side activities that are performed after the "submit" button is actually clicked (although on a side-note this is not considered best-practice because it makes the site less accessible, etc, I digress). Above all, it's important to watch your script execute and make sure that you're not getting any noticeable errors displayed on the webpage about the credentials that you're submitting.
Also, however, some websites require that you add a certain minimum amount of time between the entry of the username, password, and submitting the page in order for it to be considered a valid submitting process. I've even run in to websites that require you to use send_keys 1 at a time for usernames and passwords to avoid some anti-scraping technologies they employ. In these cases, I usually use the following between the calls:
from random import random, randint
def sleepyTime(first=5, second=10):
# returns the value of the time slept (as float)
# sleeps a random amount of time between the number variable in first
# and the number variable second (in seconds)
sleepy_time = round(random() * randint(first, second), 2)
sleepy_time = sleepy_time if sleepy_time > first else (first + random())
sleep(sleepy_time)
return sleepy_time
I don't see what use you have for making the _email and _password variables global, unless they are being changed somewhere in the login function and you want that change to be precipitated out to the other scopes.
How I would try to solve it
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException, TimeoutException
TIME_TIMEOUT = 20 # Twenty-second timeout default
def eprint(*args, **kwargs):
""" Prints an error message to the user in the console (prints to sys.stderr), passes
all provided args and kwargs along to the function as usual. Be aware that the 'file' argument
to print can be overridden if supplied again in kwargs.
"""
print(*args, file=sys.stderr, **kwargs)
def login(driver):
global _email, _password
try:
email = WebDriverWait(driver, TIME_TIMEOUT).until(EC.presence_of_element_located((By.XPATH, "//input[#id='user_email']")))
pw = WebDriverWait(driver, TIME_TIMEOUT).until(EC.presence_of_element_located((By.XPATH, "//input[#id='password']"))
pw.submit()
# if this doesn't work try the following:
# btn_submit = WebDriverWait(driver, TIME_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[#track-element='click-for-login']"))
# btn_submit.click()
# if that doesn't work, try to add some random wait times using the
# sleepyTime() example from above to add some artificial waiting to your email entry, your password entry, and the attempt to submit the form.
except NoSuchElementException as ex:
eprint(ex.msg())
except TimeoutException as toex:
eprint(toex.msg)
if __name__ == '__main__':
driver = webdriver.Chrome('/usr/bin/chromium/chromedriver',chrome_options=chrome_options)
#d.get('https://www.google.nl/')
#driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.goeventz.com/')
if login(driver) is not None:
print(create_event(driver))
For headless chrome browser you need to provide window size as well in chrome options.For headless browser selenium unable to know what your window size.Try that and let me know.
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('window-size=1920x1480')
I faced this error as well. Now check your browser if the element is inside the iframe. If so, use driver.find_element(By.CSS_SELECTOR, "#payment > div > div > iframe") and driver.switch_to.frame(iframe) Then you will be able to work out.

How to login to gmail using chrome in windows using python

i am using python script for login to gmail in chrome, but after clicking next the code returning error, can anyone please help me what's wrong, i am new to python. below is the code which i used.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
import threading
import os,time,csv,datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
a = webdriver.Chrome()
a.get("https://accounts.google.com/")
user = a.find_element_by_id("Email")
user.send_keys('username#gmail.com')
login = a.find_element_by_id("next")
login.click()
pwd = WebDriverWait(a, 10).until(EC.presence_of_element_located((By.ID, "Passwd")))
pwd.send_keys('p######')
login = a.find_element_by_id("signIn")
login.click()
clk = WebDriverWait(a, 10).until(EC.presence_of_element_located((By.LINK_TEXT, 'myaccount')))
clk.click()
logout = WebDriverWait(a, 10).until(EC.presence_of_element_located((By.ID, "gb_71")))
logout.click()
Below is the error:
Traceback (most recent call last):
File "C:\Users\mapraveenkumar\Documents\Python\gmail.py", line 20, in
clk = WebDriverWait(a, 10).until(EC.presence_of_element_located((By.LINK_TEXT, 'myaccount')))
File "C:\Users\mapraveenkumar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
That's most likely because after clicking on the "Next" button, the page takes some time to load and present the Password text field. Try using a wait statement to make sure your script waits until the element can be located.
Example:
...
login = a.find_element_by_id("next")
login.click()
pwd = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "Passwd"))
pwd.send_keys('password')
...

Resources