How can I navigate through pages using Selenium?

Navigating through pages with Selenium is fairly straightforward. Selenium WebDriver provides a convenient API to interact with the browser, whether it's Chrome, Firefox, or Safari.

Here's how to navigate through pages using Selenium in Python and JavaScript:

Python

First, you need to install selenium. You can install it via pip:

pip install selenium

Below is a simple example of how to navigate through pages:

from selenium import webdriver

# Initialize the driver
driver = webdriver.Firefox()

# Open a webpage
driver.get('http://example.com')

# Navigate to another page
driver.get('http://another.example.com')

# Go back to the previous page
driver.back()

# Go forward to the next page
driver.forward()

# Refresh the current page
driver.refresh()

# Close the browser
driver.quit()

JavaScript

First, you need to install selenium-webdriver. You can install it via npm:

npm install selenium-webdriver

Here's how you can navigate through pages:

const {Builder, By, Key, until} = require('selenium-webdriver');

(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  try {
    await driver.get('http://www.example.com');
    await driver.get('http://www.another.example.com');
    await driver.navigate().back();
    await driver.navigate().forward();
    await driver.navigate().refresh();
  } finally {
    await driver.quit();
  }
})();

In both the above Python and JavaScript examples, we first open a webpage using driver.get(). Then we navigate to another page using driver.get() again. To go back to the previous page, we use driver.back(). To go forward to the next page, we use driver.forward(). To refresh the current page, we use driver.refresh(). And finally, we close the browser using driver.quit().

Remember, driver.quit() will close all associated windows while driver.close() will close only the current window.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon