Working with Browser Navigation in Selenium using Python
Certainly! Here's a practical guide on working with browser navigation in Selenium using Python. Selenium is a powerful tool for automating web browsers, and navigating through pages is a key part of most test scripts or automation flows.
🧭 Working with Browser Navigation in Selenium (Python)
🧰 Prerequisites
Before you begin, make sure you have:
Python installed
Selenium installed:
bash
Copy
Edit
pip install selenium
A WebDriver for your browser (e.g., ChromeDriver, GeckoDriver)
🚀 Basic Setup
python
Copy
Edit
from selenium import webdriver
# Setup Chrome driver (ensure chromedriver is in PATH or provide the path)
driver = webdriver.Chrome()
# Open a webpage
driver.get("https://www.example.com")
🔄 Navigation Commands
1. Open a URL
python
Copy
Edit
driver.get("https://www.example.com")
Loads a web page in the current browser window.
2. Navigate to Another Page
python
Copy
Edit
driver.get("https://www.google.com")
3. Go Back
python
Copy
Edit
driver.back()
Simulates the browser's Back button. Useful when navigating through links.
4. Go Forward
python
Copy
Edit
driver.forward()
Simulates the browser's Forward button.
5. Refresh the Page
python
Copy
Edit
driver.refresh()
Reloads the current page.
📄 Full Example Script
python
Copy
Edit
from selenium import webdriver
import time
driver = webdriver.Chrome()
# Step 1: Go to example.com
driver.get("https://www.example.com")
print("Opened example.com")
time.sleep(2)
# Step 2: Navigate to google.com
driver.get("https://www.google.com")
print("Opened google.com")
time.sleep(2)
# Step 3: Go back to example.com
driver.back()
print("Went back to example.com")
time.sleep(2)
# Step 4: Go forward to google.com
driver.forward()
print("Went forward to google.com")
time.sleep(2)
# Step 5: Refresh the page
driver.refresh()
print("Page refreshed")
time.sleep(2)
driver.quit()
✅ Tips for Reliable Navigation
Use time.sleep() or WebDriverWait to wait for pages to load.
Always close the browser at the end with driver.quit().
Combine navigation with element validation to ensure you're on the correct page.
🛠️ Advanced Tip: Use WebDriverWait for Dynamic Content
python
Copy
Edit
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Wait until an element is visible
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myElement"))
)📝 Summary
Action Command
Open page driver.get(url)
Go back driver.back()
Go forward driver.forward()
Refresh page driver.refresh()
Would you like help with setting up Selenium for headless mode or writing navigation tests with assertions?
Learn Selenium Python Training in Hyderabad
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment