Python selenium browser driver.back().

SeleniumAutomation TestingTesting Tools

We can navigate back in the browser with Selenium webdriver. There are multiple ways to achieve this. The back() method is used to move back to the prior browser page. This method only is applicable if we jump from webpage to another.

We can also move back in the browser with the help of a Javascript Executor in Selenium. It has the execute_script() method which allows Selenium to run Javascript commands. We have to execute the Javascript command window.history.go(-1) to go back to the previous page.

Example

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch a webpage
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
print("Current Page title: " + driver.title)
#launch another webpage
driver.get("https://www.tutorialspoint.com/questions/index.php")
print("Current Page title: " + driver.title)
#back to previous page with back()
driver.back()
print("Current Page title after back: " + driver.title)

Code Implementation with Javascript Executor.

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch a webpage
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
print("Current Page title: " + driver.title)
#launch another webpage
driver.get("https://www.tutorialspoint.com/questions/index.php")
print("Current Page title: " + driver.title)
#back to previous page with execute_script()
driver.execute_script("window.history.go(-1)")
print("Current Page title after back: " + driver.title)

Output

raja
Published on 18-Sep-2020 10:08:00
Advertisements