Python selenium script to open a webpage and click a button automatically using it’s xpath.
driver.find_element_by_xpath("XPath of the BUTTON").click()
Example script to open a webpage and click a button
In below code, we open gethowstuff.com home page and click on ‘Subscribe’ button. To use the code replace the URL with yours and replace xpath of your desired button on the webpage.
Read How to find XPath of a button in Google Chrome
import time from selenium import webdriver driver = webdriver.Chrome("C:\\Users\\srinu\\Downloads\\chromedriver_win32\\chromedriver.exe") headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"} URL='https://gethowstuff.com/' driver.maximize_window() driver.get(URL) time.sleep(5) driver.find_element_by_xpath("//*[@id='text-2']/div/form/input[3]").click()
Notes: 1. Make sure to run your code in debug mode and check how long it takes to load. I have added delay of 5 seconds before clicking the button on the web page. Adjust the delay based on your web page loading speed.
2. Replace chrome driver path with that on your PC at line 3
3. Replace URL on line 5
4. Replace XPath of the button on line 9
Example Output:
Also Read Extract all links from webpage using python selenium webdriver