How to Use Selenium with Python: Simple Guide and Example
To use
selenium with Python, first install the selenium package and a browser driver like ChromeDriver. Then, import webdriver from selenium, create a browser instance, and use it to open web pages and interact with elements.Syntax
Here is the basic syntax to start using Selenium with Python:
from selenium import webdriver: Import the webdriver module.driver = webdriver.Chrome(): Create a new Chrome browser instance.driver.get('URL'): Open a web page by URL.driver.quit(): Close the browser when done.
python
from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.example.com') driver.quit()
Example
This example opens the Python official website, prints the page title, and then closes the browser.
python
from selenium import webdriver # Create a new Chrome browser instance driver = webdriver.Chrome() # Open the Python official website driver.get('https://www.python.org') # Print the page title print(driver.title) # Close the browser driver.quit()
Output
Welcome to Python.org
Common Pitfalls
Common mistakes when using Selenium with Python include:
- Not installing the correct browser driver or not adding it to your system PATH.
- Forgetting to call
driver.quit(), which leaves the browser open. - Trying to interact with elements before the page fully loads.
- Using outdated Selenium or driver versions causing compatibility issues.
Always ensure your Selenium package and browser driver versions match your browser version.
python
from selenium import webdriver # Wrong: Not quitting the browser # driver = webdriver.Chrome() # driver.get('https://www.python.org') # print(driver.title) # Right: Always quit the browser driver = webdriver.Chrome() driver.get('https://www.python.org') print(driver.title) driver.quit()
Output
Welcome to Python.org
Quick Reference
Here is a quick reference for common Selenium with Python commands:
| Command | Description |
|---|---|
| webdriver.Chrome() | Starts a new Chrome browser session |
| driver.get(URL) | Navigates to the specified URL |
| driver.find_element(By.ID, 'id') | Finds an element by its ID |
| driver.find_element(By.NAME, 'name') | Finds an element by its name attribute |
| driver.quit() | Closes the browser and ends the session |
Key Takeaways
Install Selenium and the correct browser driver before starting.
Use webdriver to open browsers and interact with web pages.
Always close the browser with driver.quit() to free resources.
Wait for pages to load before interacting with elements.
Keep Selenium and drivers updated to avoid compatibility issues.