About this lesson
Selenium Python driver.back and driver.forward: move through browser history
Selenium Python AssignmentsBeginnerGetting Started
How it works
Chrome keeps a list of the pages a tab has visited, plus a pointer to the current one. Each driver.get() to a new address adds an entry and moves the pointer to it. driver.back() moves the pointer one step to the left and driver.forward() moves it one step to the right. The visible result is the page that is now showing.
The title you get is that of the entry the pointer has reached, which is how you prove the move worked.
The ends of the list are forgiving. When there is nothing ahead, forward() does nothing and raises nothing, and the title stays as it was. Going back past the first page you loaded lands on the blank starting page, whose address is data:, and whose title is empty.
About the assignment
The starter has already loaded Text Fields and then Buttons, so the history holds two entries and you stand on the second. You move to the first entry, report it, return to the second and report that too.
What you will do
- Call the driver method that steps back one entry.
- Print what the tab is showing now, after the label
After back:. - Call the method that steps forward one entry.
- Print the title after the label
After forward:, again reading it fresh from the driver.
Common mistakes
Printing a title read before the move
If you store
driver.titlein a variable earlier and print that variable later, you show old text. Astrdoes not update itself, so read the attribute again after each move.Calling forward() first
With nothing ahead in the history,
forward()quietly does nothing. The next title is then still Buttons, and no error tells you the call was ignored.Going back too far
One
back()too many leaves the loaded pages and ends ondata:,with an empty title. Count your steps against the number ofget()calls.
In a real test suite
A test may press back to check that a filtered list keeps its filter.
From the next lesson on you stop moving between pages and start finding things inside one page, beginning with the id locator.
Related lessons
- Visit Two Pages with driver.get()Creates the two history entries by loading two pages in a row.
- Locate a Field with By.IDStarts the locator lessons, the first step toward working inside a page.
- Read the Open WindowReads which window is open, which matters once pages open in new tabs.
To try one of these calls on any page without a task, open the Online Selenium Python Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
from selenium import webdriver
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/TextFields")
driver.get("https://testkru.com/Elements/Buttons")
# Go back, print the title, go forward, print the title
finally:
driver.quit()