How to Open Browser Using Selenium Python - Simple Guide
To open a browser using
selenium in Python, first import webdriver from selenium. Then create a browser instance like driver = webdriver.Chrome() to launch Chrome. This opens the browser window controlled by Selenium.Syntax
The basic syntax to open a browser with Selenium in Python involves importing the webdriver module and creating an instance of a browser driver.
- webdriver.Chrome(): Opens Google Chrome browser.
- webdriver.Firefox(): Opens Firefox browser.
- driver.get(url): Opens the specified URL in the browser.
python
from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.example.com')
Example
This example shows how to open the Chrome browser, navigate to a website, and then close the browser.
python
from selenium import webdriver import time # Create a Chrome browser instance driver = webdriver.Chrome() # Open a website driver.get('https://www.example.com') # Wait for 5 seconds to see the browser time.sleep(5) # Close the browser driver.quit()
Output
A Chrome browser window opens, loads https://www.example.com, stays open for 5 seconds, then closes.
Common Pitfalls
Common mistakes when opening browsers with Selenium in Python include:
- Not having the correct WebDriver executable (like
chromedriver) installed or in your system PATH. - Using outdated WebDriver versions incompatible with your browser version.
- Forgetting to call
driver.quit()to close the browser properly. - Not importing
webdrivercorrectly.
Always download the latest WebDriver for your browser and ensure it matches your browser version.
python
from selenium import webdriver # Wrong: Missing WebDriver or wrong path causes error # driver = webdriver.Chrome('/wrong/path/chromedriver') # Right: Use default if chromedriver is in PATH driver = webdriver.Chrome()
Quick Reference
Here is a quick summary of commands to open browsers with Selenium in Python:
| Command | Description |
|---|---|
| webdriver.Chrome() | Open Google Chrome browser |
| webdriver.Firefox() | Open Firefox browser |
| driver.get('url') | Navigate to the specified URL |
| driver.quit() | Close the browser and end session |
Key Takeaways
Import webdriver from selenium to control browsers in Python.
Create a browser instance like webdriver.Chrome() to open the browser.
Use driver.get(url) to open a webpage in the browser.
Always match your WebDriver version with your browser version.
Call driver.quit() to close the browser properly after testing.