How do I click a button with selenium

Question:

Hello Guys i’m tryng to click a button but is not working.
my code is like this:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.implicitly_wait(0.5)

driver.maximize_window()

driver.get("https://www.freewayinsurance.com/")

driver.implicitly_wait(0.5)

element = driver.find_element(By.ID, "zipcode")
element.send_keys("60056")

element2 = driver.find_element(By.XPATH,"//div[@class='c-hero-home-radio__form-items']//button[@Class='c-button c-button--orange' and text()='Start Quote']")
element2.click()

I will apreciate if somebody can help me please thank you

The Html looks like this:
this is the HTML

Asked By: Mrc Rblr

||

Answers:

You sure that doesn’t have any other element with the same class/name of the object you are trying to click on?

Answered By: Vitor Muniz

The following code will input your zipcode, and click the button – the page will eventually load with insurance offers. The crux here is waiting for the element to load properly in page:

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

chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('disable-notifications')
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://www.freewayinsurance.com/'


browser.get(url) 
zipcode_field = WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='zipcode']")))
zipcode_field.click()
zipcode_field.send_keys('90210')
print('Beverly Hills')
button = WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Start Quote']")))
button.click()
print('searching for insurance')

The selenium setup is for Linux, but you can adapt it to your own setup, just note the imports and the part after defining the browser/driver. It will also print out in terminal:

Beverly Hills
searching for insurance

Selenium docs 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.