Forward, Back and Refresh Methods

In Selenium with Python, you can use the back(), forward(), and refresh() methods to navigate through browser history and reload pages. Here’s a quick overview of how to use them

Example Code

from selenium import webdriver
import time

# Initialize the WebDriver (e.g., using Chrome)
driver = webdriver.Chrome()

# Navigate to a URL
driver.get("https://www.google.com")
print("Initial URL:", driver.current_url)

# Navigate to another URL
driver.get("https://www.facebook.com")
print("Navigated to:", driver.current_url)

# Go back to the previous page
driver.back()
print("Back to:", driver.current_url)
# Back URL should be www.google.com

# Wait for 2 seconds
time.sleep(2)

# Move forward in the browser history
driver.forward()
print("Forward to:", driver.current_url)
# Move forward url to www.facebook.com

# Wait for 2 seconds
time.sleep(2)

# Refresh the current page ( facebook.com )
driver.refresh()
# Refresh facebook URL
print("Page refreshed at:", driver.current_url)

# Close the browser
driver.quit()

Results:

Initial URL: https://www.google.com/
Navigated to: https://www.facebook.com/
Back to: https://www.google.com/
Forward to: https://www.facebook.com/
Page refreshed at: https://www.facebook.com/

Explanation:

  • driver.back(): Navigates back to the previous page in the browser history.
  • driver.forward(): Moves forward in the browser history.
  • driver.refresh(): Refreshes/reloads the current page.