How to use Selenium in Python• 1 min
Selenium is a browser automation tool that allows you to automate interactions with web browsers in Python. You can use Selenium to automate tasks such as filling out forms, clicking buttons, and navigating through pages on a website.
Here are the basic steps to use Selenium in Python:
- Install Selenium by running
pip install selenium
- Import the necessary Selenium modules into your Python script.
from selenium import webdriver
- Create a webdriver instance to interact with the browser.
driver = webdriver.Chrome()for example.
- Use the driver to navigate to a website by calling the
- Use the driver's methods such as
find_element_by_xpath()etc. to locate elements on the page.
- Interact with the elements using the
- Close the browser by calling the
.quit()method on the driver
Here's an example of how to use Selenium to automate the task of filling out a form on a website:
from selenium import webdriver # create a new Chrome browser driver = webdriver.Chrome() # navigate to the website driver.get("https://www.example.com/") # locate the form elements name_field = driver.find_element_by_id("name") email_field = driver.find_element_by_id("email") # fill out the form name_field.send_keys("John Smith") email_field.send_keys("[email protected]") # submit the form submit_button = driver.find_element_by_xpath("//input[@type='submit']") submit_button.click() # close the browser driver.quit()
It's worth noting that Selenium can also be used to automate other browsers such as Firefox, Edge, Safari and it also provide a way to run scripts on multiple browsers at the same time.
It's also worth noting that Selenium requires a web driver to interact with the browser, in the example above we use Chrome driver but it's available for different browsers too.