python logo

selenium click button


Python hosting: Host, run, and code Python in the cloud!

Selenium can automatically click on buttons that appear on a webpage. In this example we will open a site and click on a radio button and submit button.

Related course
Browser Automation with Python Selenium

Selenium button click
Start by importing the selenium module and creating a web driver object. We then use the method:


drivers.find_elements_by_xpath(path)

to find the html element. To get the path, we can use chrome development tools (press F12). We take the pointer in devtools and select the html button we are interested in. The path will then be shown, as the example screenshot:

find_element_by_xpath Find element by xpath, using chrome dev tools
After we have the html object, we use the click() method to make the final click.
Full code:


from selenium import webdriver
import time

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.binary_location = "/usr/bin/chromium"
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://codepad.org')

# click radio button
python_button = driver.find_elements_by_xpath("//input[@name='lang' and @value='Python']")[0]
python_button.click()

# type text
text_area = driver.find_element_by_id('textarea')
text_area.send_keys("print('Hello World')")

# click submit button
submit_button = driver.find_elements_by_xpath('//*[@id="editor"]/table/tbody/tr[3]/td/table/tbody/tr/td/div/table/tbody/tr/td[3]/input')[0]
submit_button.click()

Download Selenium Examples

BackNext





Leave a Reply: