Click button using Selenium Python - python

I am new to python selenium. I want to click the Iniciar session(Login button) on this web site. I have tried using the XPath, CSS selector, CSS Path, and class name.
I use the below code to click the button:
from selenium import webdriver
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless')
driver = webdriver.Chrome("C:/Users/pralo/Downloads/DE/chromedriver", chrome_options=options)
driver.get('https://www.panamacompra.gob.pa/Inicio/#/')
sleep(10)
driver.find_element(By.XPATH,'//button[text()=" Iniciar sesión"]').click()
I get the below error for the above code execution:
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (389, 1470)
Can anyone help me understand the reason for this error?

You can utilize the driver.execute_script() method:
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
driver = webdriver.Chrome()
driver.get('https://www.panamacompra.gob.pa/Inicio/#/')
sleep(10)
element = driver.find_element(By.CLASS_NAME, 'btn-blue-dark')
driver.execute_script("arguments[0].click();", element)
The driver.execute_script() method allows you to run JavaScript code in your Python program!

Related

Trying to locate an element in a webpage but getting NoSuchElementException

I am trying to get the webdriver to click a button on the site random.org The button is a generator that generates a random integer between 1 and 100. It looks like this:
After inspecting the webpage, I found the corresponding element on the webpage looks something like this:
It is inside an iframe and someone suggested that I should first switch over to that iframe to locate the element, so I incorporated that in my code but I am constantly getting NoSuchElementException error. I have attached my code and the error measage below for your reference. I can't understand why it cannot locate the button element despite referencing the ID, which is supposed to unique in the entire document.
The code:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Edge()
driver.get("https://www.random.org/")
driver.implicitly_wait(15)
driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))
button = driver.find_element(By.CSS_SELECTOR, "input[id='hnbzsqjufzxezy-button']")
button.click()
The error message:
Make sure that there are no more Iframes on the page. If there are a few an not only one do this:
iframes = driver.find_elements(By.CSS, 'iframe')
// try switching to each iframe:
driver.switch_to.frame(iframes[0])
driver.switch_to.frame(iframes[1])
You can't find the button because its name contain random letters. Every time you will refresh the page you can see that the name value will change. So, do this:
button = driver.findElement(By.CSS, 'input[type="button"][value="Generate"]')
button.click()
There are several issues with your code:
First you need to close the cookies banner
The locator of the button is wrong. It's id is dynamic.
You need to use WebDriverWait to wait for elements clickability.
The following code works:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
url = 'https://www.random.org/'
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[onclick*='all']"))).click()
wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[id*='button']"))).click()

How to accept cookies popup within #shadow-root (open) using Selenium Python

I am trying to press the accept button in a cookies popup in the website https://www.immobilienscout24.de/
Snapshot:
I understand that this requires
driver.execute_script("""return document.querySelector('#usercentrics-root')""")
But I can't trickle down the path to the accept button in order to click it. Can anyone provide some help?
This is one way (tested & working) you can click that button: please observe the imports, as well as the code after defining the browser/driver:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
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
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('disable-notifications')
import time as t
webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
actions = ActionChains(browser)
url = 'https://www.immobilienscout24.at/regional/wien/wien/wohnung-kaufen'
browser.get(url)
page_title = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a[title='Zur Homepage']")))
actions.move_to_element(page_title).perform()
parent_div = WebDriverWait(browser, 20000).until(EC.presence_of_element_located((By.ID, "usercentrics-root")))
shadowRoot = browser.execute_script("return arguments[0].shadowRoot", parent_div)
try:
button = WebDriverWait(shadowRoot, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='uc-accept-all-button']")))
button.click()
print('clicked')
except Exception as e:
print(e)
print('no click button')
That page is reacting to user's behavior, and it will only fully load the page once it detects mouse movements, hence the ActionChains() part of the code. After that, we drill down into the shadow root element, we locate the button (using Waits, to make sure it's clickable), and then we click it.
Selenium documentation can be found at https://www.selenium.dev/documentation/
The element Alle akzeptieren within the website is located within a #shadow-root (open).
Solution
To click on the element Alle akzeptieren you have to use shadowRoot.querySelector() and you can use the following Locator Strategy:
Code Block:
driver.execute("get", {'url': 'https://www.immobilienscout24.de/'})
time.sleep(10)
item = driver.execute_script('''return document.querySelector('div#usercentrics-root').shadowRoot.querySelector('button[data-testid="uc-accept-all-button"]')''')
item.click()

I want to click on a button with Selenium

I´m trying to web scraping and i need to simulate a click on a buttoN, I´ve tried this:
url = "https://apps5.mineco.gob.pe/transparencia/mensual/default.aspx?y=2021&ap=ActProy"
driver = driver = webdriver.Chrome()
driver.get(url)
nivelGob = driver.find_element_by_xpath('//*[#id="ctl00_CPH1_BtnTipoGobierno"]')
nivelGob.click()
and returns me this error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="ctl00_CPH1_BtnTipoGobierno"]"}
(Session info: chrome=88.0.4324.190)
I've been trying find the element by css selector, class name but nothing.
This is the button:
I hope someone can help me. Thanks a lot.
The website is actually within another frame so you need to switch to that frame. Try this:
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
import time
url = "https://apps5.mineco.gob.pe/transparencia/mensual/default.aspx?y=2021&ap=ActProy"
driver = webdriver.Chrome()
driver.get(url)
time.sleep(3)
frame = driver.find_element_by_id("frame0")
driver.switch_to.frame(frame)
w = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ctl00_CPH1_BtnTipoGobierno"))).click()
Perhaps the DOM isn't fully loaded yet. Try adding implicit wait to your driver
driver.implicitly_wait(10) # seconds

Can't click on a button using Selenium (web scrape)

I am trying to click on this button so that I can proceed to the next page but doesn't seem to be working for me. I am trying to click on the 'Search for an inspection report' button.
This is the xpath for this source. //[#id="btnOK"] . And so I was trying to use driver.find_element_by_xpath('//[#id="btnOK"]').click() and it gives me an error saying unable to locate element.
Here is the link to the site.
https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise
Any help would be great.
It is because the button is present within a different iframe. In order to click that button, u have to switch focus to that iframe. This is how u do it:
iframe = driver.find_element_by_id("iframe-form")
driver.switch_to.frame(iframe)
btn = driver.find_element_by_xpath('//*[#id="btnOK"]')
btn.click()
Plus, another thing to note is that the xpath u have provided is wrong. U have missed a * in the xpath. The right xpath is '//*[#id="btnOK"]'.
Complete code:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise')
iframe = driver.find_element_by_id("iframe-form")
driver.switch_to.frame(iframe)
btn = driver.find_element_by_xpath('//*[#id="btnOK"]')
btn.click()
Hope that this helps.
Alternative solution using webdriver wait:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('<PATH_TO_CHROMEDRIVER>', options=chrome_options)
# load page via selenium
wd.get("https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise")
# wait for iframe, switch to it
frame = WebDriverWait(wd, 30).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"iframe-form")))
# wait for button, scroll to it, click it
btn = WebDriverWait(wd, 30).until(EC.presence_of_element_located((By.ID, 'btnOK')))
wd.execute_script("arguments[0].scrollIntoView();", btn)
wd.execute_script("arguments[0].click();", btn)

Python ElementClickInterceptedException in Selenium

I'm working on a selenium based python automation project. The code automates some regular tasks by connecting to the company's internal webpage url. However, the code occasionally throws the same exception between two button click actions. Could you please help me to figure out what's the point that I miss? Thanks in advance.
You can find my code snippet and error screenshot here:
selenium.common.exceptions.ElementClickInterceptedException: Message:
element click intercepted: Element ... is not clickable at point (180,
447). Other element would receive the click: ...
pycharm_error_output_screenshot
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
from selenium.webdriver.chrome.options import Options
timeout = 200
options = Options()
options.headless = False
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(3)
wait = WebDriverWait(driver, timeout)
driver.get("https://internal_web_appplication_page_for_company_x")
apply_button_v4 = wait.until(EC.visibility_of_element_located((By.XPATH, "//body//button[2]")))
apply_button_v4.click()
both_button = wait.until(EC.element_to_be_clickable((By.XPATH, "// label[3] // span[1]")))
wait.until_not(EC.element_to_be_clickable((By.CLASS_NAME, "map-mask")))
wait.until_not(EC.element_to_be_clickable((By.XPATH, "// *[ contains( # class, 'map-mask')]")))
both_button.click()
The intercepted element is full screen "loading" notification which is visible for a short period of time following any click action.
Moreover, my code works as expected if i put time.sleep(5) before clicking "both_button".
Try below solution for clicking on both_button. There are multiple reasons of this exception like javascript or ajax call , element is not in the view port.
actions = ActionChains(driver)
actions.move_to_element(both_button)
actions.click(both_button)
actions.perform()

Categories

Resources