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.

Get Current URL

To get the current URL in Python using Selenium, you can use the current_url property of the WebDriver instance. Here’s how you can do it:

from selenium import webdriver

# Example using Chrome WebDriver
driver = webdriver.Chrome()

# Navigate to a website
driver.get("https://sqatools.in/")

# Get the current URL
current_url = driver.current_url
print("Current URL:", current_url)

# Close the browser
driver.quit()

This will print the current URL of the page that the WebDriver is on.


get_attribute Method

In Selenium with Python, the get_attribute() method is used to retrieve the value of a specific attribute from an HTML element. This can be particularly useful when you need to access values like href for links, src for images, class, id, or other attributes of HTML elements.

Basic Syntax

element = driver.find_element(By.XPATH, 'your_xpath_here')
attribute_value = element.get_attribute('attribute_name')

Example Usage

Here’s an example of how you might use get_attribute() to get the URL from a link:

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Initialize the WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(10)

#
Open a webpage
driver.get('https://sqatools.in/')

#
Find an element and get its attribute
element = driver.find_element(By.XPATH, "//a[text()='Python Tutorials']")
href_value = element.get_attribute('href')

print("The link URL is:", href_value)

#
Close the WebDriver
driver.quit()

In this example:

  • driver.find_element(By.XPATH, ‘//a[text()=’Python Tutorials’]’) locates an element with the XPath specified.
  • element.get_attribute(‘href’) retrieves the href the attribute value of the located <a> (anchor) element.

Common Use Cases

  • href for link URLs
  • src for image URLs
  • class for CSS class names
  • id for unique identifiers
  • data-* attributes for custom data

PyCharm & VS Code Setup

Python Tutorial › Getting Started › PyCharm & VS Code Setup

PyCharm & VS Code Setup

BeginnerLesson 4 of 479 min read1 runnable examples

An IDE (integrated development environment) gives you autocomplete, error highlighting, a run button and a debugger. This lesson sets up the two most popular free choices, PyCharm and Visual Studio Code.

In this lesson
  • Create a Python project in PyCharm
  • Set up VS Code with the Python extension
  • Select the right interpreter
  • Run and debug a script with breakpoints

Which editor should you choose?

PyCharm (Community or Pro)VS Code + Python extension
Made forPython onlyMany languages
SetupWorks out of the boxInstall the Python extension
StrengthsRefactoring, inspections, test runnerLightweight, huge extension library
Best forPython-focused learners and teamsPeople who also write JavaScript, YAML, etc.

Both are free for learning. Pick one and stick with it while you learn; the Python you write is the same.

Set up PyCharm

  1. Download PyCharm from jetbrains.com and install it.
  2. Click New Project. Give it a name such as python-practice.
  3. Under Interpreter type choose Project venv. PyCharm creates a virtual environment (a private copy of Python for this project) in a .venv folder.
  4. Click Create. Right-click the project folder, choose New > Python File, and name it first.py.
  5. Paste the program below and click the green Run arrow next to the first line.

Set up VS Code

  1. Install Visual Studio Code from code.visualstudio.com.
  2. Open the Extensions view (Ctrl+Shift+X), search for Python and install the extension published by Microsoft. It also installs Pylance for autocomplete.
  3. Use File > Open Folder to open an empty folder for your practice files.
  4. Press Ctrl+Shift+P, run Python: Create Environment, choose Venv and your installed Python.
  5. Create first.py, paste the program below and press the Run Python File triangle in the top right.

Your first program in the IDE

first.py
total = 0for price in [120, 80, 45]:    total = total + price    print("Running total:", total) print("Final total:", total)
Output
Running total: 120
Running total: 200
Running total: 245
Final total: 245
Tip

The Run window shows the same output as the terminal. If you see a ModuleNotFoundError for a package you installed, the IDE is using a different interpreter. Check the interpreter name in the bottom-right status bar.

Debug with a breakpoint

A breakpoint pauses the program on a line so you can inspect variables.

  1. Click in the gutter left of the line total = total + price. A red dot appears.
  2. Start the program with Debug (the bug icon) instead of Run.
  3. The program stops at the red dot. The Variables panel shows price and total.
  4. Press Step Over (F8 in PyCharm, F10 in VS Code) to run one line at a time and watch total grow.
Note

Debugging is the fastest way to understand someone else’s code, including the practice program solutions on this site. Step through a solution and watch each variable change.

Useful shortcuts

ActionPyCharmVS Code
Run current fileShift+F10Ctrl+F5
DebugShift+F9F5
Comment / uncomment lineCtrl+/Ctrl+/
Reformat codeCtrl+Alt+LShift+Alt+F
Find anythingShift ShiftCtrl+P

Check your understanding

Quick quiz

1. What does a virtual environment give your project?

2. Where do you set a breakpoint?

3. A package works in the terminal but the IDE says ModuleNotFoundError. What is the likely cause?

Program Practice

Create a basic-programs folder in your project and solve each program in its own file.

IDE setup FAQ

Is PyCharm Community Edition free?

Yes. PyCharm has a free tier for Python development, and VS Code with the Python extension is free as well.

Can I use IDLE instead?

Yes. IDLE comes with Python and is fine for small scripts. Move to PyCharm or VS Code when you want a debugger, a test runner and Git support.

What is a Python interpreter in PyCharm?

It is the Python executable PyCharm uses to run your code, usually the one inside the project’s .venv folder. You can change it in Settings > Project > Python Interpreter.

Install Python

Python Tutorial › Getting Started › Install Python

Install Python

BeginnerLesson 3 of 478 min read1 runnable examples

To write your own Python programs you need the Python interpreter on your computer. This lesson installs it on Windows, macOS or Linux, checks that it works, and runs your first script.

In this lesson
  • Install Python 3 on your OS
  • Check the installed version
  • Use the interactive shell
  • Run a .py file from the terminal

Check whether Python is already installed

Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and run:

Terminal
$ python --versionPython 3.15.1

If you see a version number that starts with 3, Python is ready and you can skip to the interactive shell.

Note

On macOS and Linux the command may be python3 instead of python. On Windows, the py launcher (py --version) is installed alongside Python and picks the newest version for you.

Install Python on Windows

  1. Go to python.org, open Downloads and download the latest Python 3 installer for Windows.
  2. Run the installer. On the first screen tick Add python.exe to PATH. This lets you type python in any terminal.
  3. Click Install Now and wait for it to finish.
  4. Close and reopen your terminal, then run python --version again.
Watch out

If python opens the Microsoft Store instead of printing a version, PATH was not set. Re-run the installer, choose Modify, and tick Add Python to environment variables, or turn off the “App execution aliases” for python.exe in Windows Settings.

Install Python on macOS

  1. Download the macOS installer from python.org and run the .pkg file, or install with Homebrew: brew install python.
  2. Open Terminal and run python3 --version.

Install Python on Linux

Most Linux distributions already include Python 3. If yours does not, install it with the package manager:

  • Ubuntu or Debian: sudo apt install python3 python3-pip python3-venv
  • Fedora: sudo dnf install python3

The interactive shell (REPL)

Type python on its own to start the interactive shell. It shows a >>> prompt, runs each line as soon as you press Enter and prints the result:

Python shell
>>> 2 + 35>>> "py" * 3'pypypy'>>> exit()

The shell is perfect for trying one line. For anything longer, write a file.

Run your first Python file

Create a file called hello.py in any folder with this content:

hello.py
print("Hello from a Python file!")print("2 to the power 10 is", 2 ** 10)
Output
Hello from a Python file!
2 to the power 10 is 1024

Then run it from a terminal opened in that folder:

Terminal
$ python hello.pyHello from a Python file!2 to the power 10 is 1024
Tip

Python files always end in .py. Keep each practice program in its own file with a descriptive name such as list_sum.py, so you can find and re-run it later.

Install packages with pip

pip installs extra packages from PyPI, the Python Package Index. It comes with Python. Check that it works:

Terminal
$ python -m pip --versionpip 26.2.2 from C:\Python3\Lib\site-packages\pip (python 3.15)

You install a package with python -m pip install <name>, for example python -m pip install requests. The Modules & pip lesson covers this in detail, including virtual environments.

Check your understanding

Quick quiz

1. Which installer option lets you type python in any Windows terminal?

2. What does the >>> prompt mean?

3. Which command installs a package?

Program Practice

With Python installed, write each basic program in its own .py file and run it from the terminal.

Install Python FAQ

Which Python version should I install?

Install the newest Python 3 release from python.org. Libraries add support for new versions quickly, and every example in this tutorial works on current Python 3.

What is the difference between python and python3?

They are names for the interpreter. On Windows the command is usually python (or py). On macOS and many Linux systems python3 is the Python 3 interpreter and python may not exist.

Do I need an IDE to write Python?

No. Any text editor and a terminal are enough. An IDE such as PyCharm or VS Code adds autocomplete, debugging and a run button. See PyCharm & VS Code Setup.

How do I uninstall Python on Windows?

Open Settings > Apps > Installed apps, find Python 3.x and click Uninstall. Remove the Python Launcher the same way if you want it gone too.

Get Text Selenium Method

In Selenium with Python, the text method retrieves the visible text from a web element. This is useful when you need to get the content of an element like a <div>, <span>, <p>, or any other HTML tag that contains text.

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Initialize the WebDriver (this example uses Chrome)
driver = webdriver.Chrome()

#
Open a webpage
driver.get("https://sqatools.in/dummy-booking-website/")

#
Locate the element containing the header of website
element = driver.find_element(By.TAG_NAME, "h1")

#
Get the heading text from the element
text_content = element.text

#
Print the text content
print(text_content) # Dummy Ticket Booking Website

#
Close the browser
driver.quit()

Steps:

  1. Initialize the WebDriver: Start the WebDriver for the browser you want to use.
  2. Navigate to the webpage: Use driver.get() to open the page where the target element is located.
  3. Find the element: Use one of the find_element methods (e.g., find_element(By.ID, By.XPATH, By.CLASS_NAME)) to locate the element.
  4. Retrieve the text: Use the text method on the element to get its visible text.
  5. Display or use the text: The text attribute returns the text as a string, which you can print or use in your logic.

Example using XPath:

element =driver.find_element(By.XPATH,"//div[@class='example-class']")
text_content = element.text
print(text_content)

Important Notes:

  • The text method only retrieves visible text: If the text is hidden via CSS (display: none, visibility: hidden;, etc.), Selenium will not retrieve it.
  • Whitespace handling: The text method preserves the text formatting as it appears in the browser, so you may get extra spaces or line breaks.

click Method

In Selenium with Python, the click() method is used to simulate a mouse click on a web element, like a button, link, or any other clickable element. Before using the click() method

Here’s a basic example of how to use click():

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

#
Initialize WebDriver (this example uses Chrome)
driver = webdriver.Chrome()

#
Open a webpage
driver.get("https://www.facebook.com")

#
Locate the element and click it (by ID)
element = driver.find_element(By.ID, "login")
element
.click()

#
Close the browser
driver.quit()

Steps to use click():

  1. Initialize the WebDriver: Start by setting up the WebDriver for the browser you are automating (e.g., Chrome, Firefox).
  2. Navigate to the webpage: Use driver.get() to load the webpage.
  3. Find the element: Use one of the find_element methods (e.g., find_element(By.ID, By.XPATH, By.NAME)) to locate the web element.
  4. Perform the click action: Call the click() method on the located element.

Common Locators:

  • By.ID: Locate by element’s ID.
  • By.XPATH: Locate using XPath.
  • By.NAME: Locate by element’s name attribute.
  • By.CLASS_NAME: Locate by element’s class name.
  • By.TAG_NAME: Locate by element’s tag name.

Example with XPath:

element = driver.find_element(By.XPATH, "//button[@class='submit']")
element.click()

Ensure that the element you are trying to click is visible and interactable. Sometimes, you may need to wait for the element to load, which can be done using Selenium’s WebDriverWait:

Using WebDriverWait:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#
Wait for the element to be clickable
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "submit-button"))
)

element.click()

This example waits up to 10 seconds for the element to be clickable before performing the click action.


send_keys Method

The send_keys() method in Selenium is used to simulate typing text into input fields or elements such as text boxes, text areas, or other editable elements in web pages. It can also be used to send special keys like Enter, Tab, or Arrow keys by using the Keys class from selenium.webdriver.common.keys.

Syntax:

element.send_keys("text to input")

Example 1: Sending text to an input field

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

#
Locate the input field
input_element = driver.find_element(By.NAME, 'q')

#
Send text to the input field
input_element.send_keys("Python Selenium")

#
Close the browser
driver.quit()

Example 2: Using special keys (e.g., Enter key)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

#
Locate the input field
input_element = driver.find_element(By.NAME, 'q')

#
Send text and press Enter
input_element.send_keys("search query", Keys.ENTER)

#
Close the browser
driver.quit()

Common Use Cases:

  • Filling forms by sending text to multiple input fields.
  • Simulating keyboard actions such as pressing Enter, Tab, or navigating using arrow keys.

Selenium Waits

Selenium is an incredibly useful tool for automating web testing, but dealing with web elements that load dynamically can sometimes be tricky. This is where Selenium waits come into play.

Understanding Selenium Waits

Selenium waits allow you to manage timing issues and ensure that your script interacts with elements only when they’re ready. In this article, we’ll explore the different types of waits in Selenium, how to use them, and why they are essential in building robust automated tests.

Why Do We Need Waits in Selenium?

One of the biggest challenges in web automation is dealing with dynamic content that loads at different speeds. If your script tries to interact with an element that hasn’t loaded yet, it can throw an error. To solve this, Selenium provides different types of waits to pause your script and give the page time to load before continuing.


Types of Selenium Waits

Selenium offers three primary types of waits to deal with dynamic web elements:

  1. Implicit Waits
  2. Explicit Waits
  3. Fluent Waits

Let’s break down how each of these waits works.


1. Implicit Waits Explained

An Implicit Wait tells Selenium to wait for a specific amount of time before throwing an exception if an element isn’t found. This is like setting a blanket timeout for all the elements in your script.

How Implicit Waits Work

When you set an implicit wait, Selenium will pause the script for the given time, say 10 seconds, until the desired element becomes available. If it finds the element within that time, it proceeds. If not, it throws an exception


2. Explicit Waits Explained

Unlike implicit waits, Explicit Waits let you specify certain conditions under which Selenium should wait. Instead of just waiting for an element, it waits for a specific condition, like “element to be clickable” or “element to be visible.”

How Explicit Waits Work

You can define a condition in your script, and Selenium will keep checking for that condition to be met before interacting with the element. You can set both the condition and the maximum wait time.


3. Fluent Waits Explained

Fluent Waits offer more control by allowing you to set a polling interval, which determines how frequently Selenium checks if the condition is met. This wait is a more advanced form of explicit wait.

How Fluent Waits Differ from Explicit Waits

While both are condition-based waits, Fluent Waits let you customize the wait by defining the frequency with which Selenium checks the condition. Fluent waits are useful when you expect a delay but don’t want Selenium to keep waiting unnecessarily.

Using Polling Intervals with Fluent Waits

Fluent waits allow you to set a polling interval, like checking every 500 milliseconds, and can also ignore specific exceptions while waiting, which adds an extra layer of control to your tests.


Code Examples for Selenium Waits

Here are some practical examples of how to use different waits in Selenium with Python.

Using Implicit Waits in Python

from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) #
Set an implicit wait of 10 seconds
driver.get("https://sqatools.in/dummy-booking-website/")

Using Explicit Waits in Python

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
#
Lauch chrome browser and open dummy website
driver.get("https://sqatools.in/dummy-booking-website/")

#
Wait up to 10 seconds for the element to be clickable
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "login-username"))
)
element.click()
driver.close()

Using Fluent Waits in Python

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://sqatools.in/dummy-booking-website/")

#
Fluent wait example with a polling interval of 500 milliseconds
wait = WebDriverWait(driver, 10, poll_frequency=0.5, ignored_exceptions=[Exception])

#
Wait for an element to be clickable
element = wait.until(EC.element_to_be_clickable((By.ID, "login-btn")))
element.click()
driver.close()



Dummy Booking Website

Practice end-to-end flight booking for automation testing: log in, search flights, pick a flight and seats, enter passenger details and pay with dummy test data. Every element has a stable id and data-testid for Selenium and Playwright practice.

Dummy Ticket Booking Website

SkyTrip practice airline: a safe, fake booking flow for automation testing. No real flights or payments.
Signed in as Test User
  1. 1Search
  2. 2Select flight
  3. 3Passengers
  4. 4Seats
  5. 5Payment
  6. 6Confirmation

Select your flight

Traveller details

Enter names exactly as on the passport or ID. All fields marked * are required.

Contact details

Choose your seats

Pick a seat for each traveller on each flight. Infants sit on an adult’s lap.

FreeExtra legroom ₹800 OccupiedSelected traveller Your other travellers

Review and pay

This is a dummy payment. Only the test details listed below are accepted.

Practice only: use card 4111 1111 1111 1111, UPI success@upi or any bank. Do not enter real card details.
Processing payment…