Can't click a button in python

Question:

Good afternoon everyone,
I am new to doing Web Scraping in Python, I would appreciate it if you could help me solve this problem that is occurring to me when clicking on a button (I have been able to do it in others), below is my code:

opts = webdriver.ChromeOptions()
opts.add_argument("user-agent=Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36")
driver = webdriver.Chrome('C:/Users/JSALINA/Documents/chromedriver.exe', options=opts)

driver.maximize_window()
time.sleep(2)
driver.get('https://fasecolda.com/ramos/automoviles/historial-de-accidentes-de-vehiculos-asegurados/')

time.sleep(3)
driver.find_element(By.XPATH, '//*[@id="form"]/div/div/div/div[2]/div/div/div/div/span').click()

The error it shows is the following:

enter image description here

The button I’m trying to click is this:

enter image description here

Thank you very much in advance for your kind cooperation.

Cheers

Asked By: Jhonar Salina

||

Answers:

That button is in an iframe. It would also be wise to wait that element to be clickable, before trying to locate and click it. The example below will work, setup is for linux, but you just have to observe the imports, and part after defining the browser.

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.keys import Keys
import time as t

chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("window-size=1280,720")
webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)

url = 'https://fasecolda.com/ramos/automoviles/historial-de-accidentes-de-vehiculos-asegurados/'
browser.get(url)

WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//*[@title='Términos']")))
t.sleep(3)
print('switched to iframe')
button = WebDriverWait(browser,5).until(EC.element_to_be_clickable((By.XPATH, '//*[text()="Acepto los Términos y Condiciones"]')))
print('located the button')
button.click()
print('clicked the button')
try:
    button.click()
    print('clicked the button again')
except Exception as e:
    print('nevermind, click registered the first time')

For some reason, I had to click it twice to register.

Selenium documentation can be found at https://www.selenium.dev/documentation/

Answered By: platipus_on_fire
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.