A quick look at some options when you want to click buttons on a webpage using Python and Selenium.
Firstly as always, we’ll start with a basic script that visits a page:
from selenium import webdriver
url = 'https://www.moneyhelper.org.uk'
driver = webdriver.Safari()
driver.get(url)
This will open the web browser and visit the url we specified.
Next we’ll add the CSS selector of the button we want to click, in this case its he button which accepts the site cookies:
button_selector = 'button#ccc-notify-accept'
Because of the way we are selecting the element we need to import the ‘By’ module from selenium:
from selenium.webdriver.common.by import By
Now we’ll place the button element into an object:
button = driver.find_element(By.CSS_SELECTOR, button_selector)
Now we have the button, we can look at some options for clicking on it.
Option 1: Straight up click!
button.click()
Option 2: JavaScript click
driver.execute_script("arguments[0].click();", button)
Putting it all together
# Import webdriver and By modules from selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
# Specify the URL and driver
url = 'https://www.moneyhelper.org.uk'
driver = webdriver.Safari()
# Visit the page
driver.get(url)
# Target the button element
button_selector = 'button#ccc-notify-accept'
button = driver.find_element(By.CSS_SELECTOR, button_selector)
# Option 1 - Click
button.click()
# Option 2 - Script click
driver.execute_script("arguments[0].click();", button)