When using Selenium for automated testing or web scraping, retrieving the page title is a common requirement. The page title helps verify proper page loading or confirm that you are on the intended page. Below are the steps to retrieve the page title in Selenium:
Step 1: Install and Configure Selenium
First, ensure that the Selenium library and the appropriate web drivers (such as ChromeDriver, GeckoDriver, etc.) are installed. This can be achieved using the pip command in Python:
bashpip install selenium
Step 2: Import Selenium WebDriver
In a Python script, import the WebDriver module:
pythonfrom selenium import webdriver
Step 3: Create a WebDriver Instance
Next, create a WebDriver instance specifying the browser. For example, if using Chrome:
pythondriver = webdriver.Chrome()
Step 4: Open a Web Page
Use the get method to load the target web page:
pythondriver.get("https://www.example.com")
Step 5: Retrieve the Page Title
Now, use the title attribute to obtain the title of the currently loaded page:
pythontitle = driver.title print("Page title is:", title)
Example
Combine the above steps into a simple Python script to retrieve and print a web page's title:
pythonfrom selenium import webdriver # Create WebDriver instance driver = webdriver.Chrome() # Open the web page driver.get("https://www.example.com") # Retrieve and print the page title print("Page title is:", driver.title) # Clean up and close the browser driver.quit()
This script imports necessary modules, initializes the Chrome WebDriver, opens the specified URL, retrieves the page title and prints it, and finally closes the browser to release resources.
Using this approach, retrieving and verifying web page titles in automation scripts is highly convenient, which is crucial for ensuring the quality and correctness of web applications.