How to handle the browsing history in Selenium?
In this article we will discuss how to handle the web browsing history in selenium.
In Browser toolbar, we can do back, forward, and refresh. Therefore, in this case study, we will demo how back, forward, and refresh can be done in selenium.
Key API in Selenium
- driver.back()
- driver.forward()
- driver.refresh()
Here are the key Selenium API we will use to do browsing history back, forward, and refresh.
Testing Scenario
- Visit www.google.com
- Search “selenium webdriver“
- Click one of search results, “Selenium WebDriver”
- Back
- Search Title = “selenium webdriver – Google Search”
- Forward
- Search “Selenium WebDriver”
- Refresh
- Search “Selenium WebDriver”
Sample Code
[pastacode lang=”python” message=”Browsing History Handling in Selenium” highlight=”37,47,53″ provider=”manual”]
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
class NavigationTest(unittest.TestCase):
def setUp(self):
# create a new Firefox session
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://www.google.com")
def testBrowserNavigation(self):
driver = self.driver
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
search_field.send_keys("selenium webdriver")
search_field.submit()
# click the SElenium WebDriver link
se_wd_link = driver.find_element_by_link_text("Selenium WebDriver")
se_wd_link.click()
# Verify if the target window title is "Selenium WebDriver"
self.assertEqual("Selenium WebDriver", driver.title)
# Click Back to previous page. It's google search result in this case.
driver.back()
# Verify if it's google search results with title "Selenium WebDriver - Google"
self.assertTrue(WebDriverWait(self.driver, 30).until(expected_conditions.title_contains("Selenium WebDriver - Google")))
# Click Forward. It should be the Selenium WebDriver page.
driver.forward()
self.assertTrue(WebDriverWait(self.driver, 10).until(expected_conditions.title_is("Selenium WebDriver")))
# Click Refresh to load the page again.
driver.refresh()
self.assertTrue(WebDriverWait(self.driver, 10).until(expected_conditions.title_is("Selenium WebDriver")))
def tearDown(self):
# close the browser window
self.driver.quit()
if __name__ == '__main__':
unittest.main()
[/pastacode]