0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Open URL in Selenium Python: Simple Guide

To open a URL in Selenium Python, first create a WebDriver instance, then use the get() method with the URL string. For example, driver.get('https://example.com') opens the specified webpage in the browser controlled by Selenium.
๐Ÿ“

Syntax

The basic syntax to open a URL in Selenium Python involves creating a WebDriver object and calling its get() method with the URL as a string.

  • driver: The WebDriver instance controlling the browser.
  • get(url): Method to navigate the browser to the specified URL.
python
from selenium import webdriver

# Create a WebDriver instance (e.g., Chrome)
driver = webdriver.Chrome()

# Open the URL
url = 'https://example.com'
driver.get(url)
๐Ÿ’ป

Example

This example shows how to open the URL https://example.com using Selenium with the Chrome browser. It launches the browser, opens the page, waits 5 seconds to see the page, then closes the browser.

python
from selenium import webdriver
import time

# Initialize Chrome WebDriver
driver = webdriver.Chrome()

# Open the URL
driver.get('https://example.com')

# Wait for 5 seconds to view the page
time.sleep(5)

# Close the browser
driver.quit()
Output
Browser window opens https://example.com, stays open for 5 seconds, then closes.
โš ๏ธ

Common Pitfalls

Common mistakes when opening URLs in Selenium Python include:

  • Not initializing the WebDriver before calling get().
  • Using an incorrect or unsupported WebDriver executable.
  • Forgetting to quit the driver, which leaves browser windows open.
  • Passing an invalid URL string or missing the protocol (e.g., https://).

Always ensure the WebDriver executable (like chromedriver) is installed and in your system PATH or specify its location.

python
from selenium import webdriver

# Wrong: calling get() before driver initialization
# driver.get('https://example.com')  # This will cause an error

# Right way:
driver = webdriver.Chrome()
driver.get('https://example.com')
๐Ÿ“Š

Quick Reference

Summary tips for opening URLs in Selenium Python:

  • Always create a WebDriver instance before opening URLs.
  • Use driver.get('url') to navigate.
  • Include the full URL with protocol (http:// or https://).
  • Close the browser with driver.quit() after tests.
โœ…

Key Takeaways

Create a WebDriver instance before opening any URL.
Use driver.get('https://example.com') to open the webpage.
Always include the full URL with protocol (http or https).
Remember to close the browser with driver.quit() to free resources.
Ensure the WebDriver executable is correctly installed and accessible.