How to click element using selenium web driver(Python) - python-3.x

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()

Related

Scroll to right in Tradingview chart using python

I am trying to scroll right using selenium python in TradingView
My Code:
driver.find_element_by_xpath("//div[#class='control-bar__btn control-bar__btn--move-right apply-common-tooltip']").click()
It throws an error:
selenium.common.exceptions.ElementNotInteractableException: Message:
element not interactable
Try the below code -
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 60)
action = ActionChains(driver)
driver.maximize_window()
driver.get('https://www.tradingview.com/chart/')
try:
wait.until(EC.visibility_of_element_located((By.XPATH, "//span[contains(#class,\"closeIcon\")]"))).click()
except:
pass
RightScroll = wait.until(EC.presence_of_element_located((By.XPATH,"//div[contains(#class,\"btn--move-right\")]")))
for i in range(10):
time.sleep(2)
print(i)
action.move_to_element(RightScroll).click().perform()
If it solves your problem then please mark it as answer. Do let me know if you have any query.
There is a message window displayed when you first load the page. You have to close it first (to get the right arrow container visible) if you are not doing it by
driver.findElement(By.xpath(".//span[contains(#class,'closeIcon')]")).click();
driver.findElement(By.xpath(".//td[#class='chart-markup-table time-axis']")).click();//To get the right arrow container visible
driver.findElement(By.xpath(".//div[#class='control-bar__btn control-bar__btn--move-right apply-common-tooltip']")).click();

Element not interactable error in python ,selenium

the code:
import time
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 selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome(r"C:\Users\Desktop\chromedriver.exe")
browser.get('https://www.youtube.com/')
browser.maximize_window()
search = browser.find_element_by_name('search_query')
time.sleep(5)
search.send_keys("shakira waka waka")
search.send_keys(Keys.RETURN)
time.sleep(5)
browser.find_element_by_class_name("style-scope yt-img-shadow").click()
Hello friends, I want the video to play by searching the song names and the singer name generically on the youtube search section and clicking the image that comes after it. But the program gives "element not interactable" error. How can I play the video by clicking the incoming picture?
Try the below code :
driver = webdriver.Chrome()
driver.maximize_window()
wait = WebDriverWait(driver, 10)
driver.get('https://www.youtube.com/')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[id='search']"))).send_keys("shakira waka waka")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[id='search-icon-legacy']"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ytd-video-renderer.style-scope.ytd-item-section-renderer"))).click()

How to hit the Next button from Python using Selenium?

I am trying to work with the following site using Python.
Please advise how can I hit the Next button:
I have tried the following:
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
import time
driver = webdriver.Chrome(executable_path = r'C:/chromedriver.exe')
driver.maximize_window()
wait = WebDriverWait(driver,40)
driver.get('https://www.okcupid.com/login')
driver.execute_script('arguments[0].click();',wait.until(EC.element_to_be_clickable((By.ID, 'username'))))
wait.until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys("abc")
driver.execute_script('arguments[0].click();',wait.until(EC.element_to_be_clickable((By.ID, 'username'))))
wait.until(EC.element_to_be_clickable((By.ID, 'password'))).send_keys("123")
# Find login button
login_button = driver.find_element_by_name('Next')
# Click login
login_button.click()
But got an error:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="Next"]"}
Name is a an attribute on a webelement. The next button has no Name attribute.
You can try this xpath:
//input[#value='Next']
login_button = driver.find_element_by_xpath('//input[#value="Next"]')

ElementNotInteractable Exception: Message: Element <a href=> could not be scrolled into view

I am trying to click and download "Real Sector" on the following link:
http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm
Here is what I have tried:
driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
try:
driver.find_element_by_css_selector("a[href= 'Chap-2.pdf']").click()
except NoSuchElementException:
pass
But it gives following error:
ElementNotInteractableException: Message: Element could not be scrolled into view
How can I resolve this?
You need to apply Explicit Wait and wait till the element is present on the page and then you can click on it.
You can also scroll to the element first and then click on it.
You can do it like:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
try:
element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[#href='Chap-2.pdf']")))
driver.execute_script("arguments[0].scrollIntoView();", element)
element.click()
except NoSuchElementException:
pass
OR
You can directly click on the element using java script click like:
driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
try:
element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[#href='Chap-2.pdf']")))
driver.execute_script("arguments[0].click();", element)
except NoSuchElementException:
pass
Try to wait use element_to_be_clickable
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href= 'Chap-2.pdf']")))
element.click()
To click on "Real Sector" link Induce WebDriverWait() and element_to_be_clickable() and following xpath option.
driver = webdriver.Chrome()
driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(.,'Real Sector')]"))).click()
You need to import following libraries.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
Browser snapshot after clicking.

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.

Resources