How to get Response Status Code with Selenium WebDriver?
Last Updated :
23 Aug, 2024
In web automation and testing, obtaining the HTTP response status code is crucial for validating the accessibility and health of web pages. While Selenium WebDriver is widely recognized for its powerful capabilities in automating browser interactions, it does not directly provide methods for fetching HTTP response status codes. However, you can seamlessly integrate Selenium with other tools to achieve this.
HTTP response status codes are three-digit numbers sent by the server to indicate the result of a client's request. These codes help in understanding whether a request was successful or if there were issues, such as errors or redirects. For comprehensive web testing, combining Selenium WebDriver with libraries like HttpURLConnection allows you to not only automate user interactions but also verify the status codes to ensure that your web applications are performing as expected.
Prerequisites
What is the Response Status Code?
A response status code is part of the HTTP response message sent by a server to a client's request. It indicates the result of the server's attempt to handle the request. Common status codes include:
- 200 OK: The request was successful, and the server returned the requested resource.
- 404 Not Found: The requested resource could not be found.
- 500 Internal Server Error: The server encountered an error and could not complete the request.
Why Get Response Status Codes in Selenium?
Getting response status codes is essential for:
- Validating API Responses: Ensure that backend services are responding as expected.
- Performance Monitoring: Identify issues related to server response times and availability.
- Error Handling: Check for and handle errors in web applications.
Steps to get Response Status Code with Selenium WebDriver
Step 1 : Make a new Folder ( eg: Webdriver automation). Make a libs folder inside the project.
Step 2 : Downloading dependencies is important. You need 2 main dependencies(including the JAR files) to be extracted in the libs folder.
The project library Listed below are the required dependencies:
- Selenium JAR Files: Go to Selenium website and select Java under downloads> Selenium Clients and WebDriver Language Bindings.
- WebDriverManager JAR Files: Use the below code on any Online maven download tool to get the zip folder.
XML
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.23.1</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.5.0</version>
</dependency>
</dependencies>
Step 3 : Next, extract both of these zip folders to the libs folder that we made in our project library earlier.
Step 4 : Send an HTTP Request:
Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Make a direct HTTP request using HttpURLConnection
URL url = new URL("https://www.geeksforgeeks.org/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int statusCode = connection.getResponseCode();
System.out.println("HTTP Status Code: " + statusCode);
// Check if the request was successful
if (statusCode == HttpURLConnection.HTTP_OK) {
System.out.println("Connection successful.");
} else {
System.out.println("Failed to connect, status code: " + statusCode);
}
// Set up Selenium WebDriver using WebDriverManager to handle ChromeDriver setup
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
// Initialize the ChromeDriver with the specified options
WebDriver driver = new ChromeDriver(options);
// Navigate to the URL using WebDriver
driver.get("https://www.geeksforgeeks.org/");
System.out.println("Title of the page is: " + driver.getTitle());
// Close the browser
driver.quit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 5: Compile the code by writing the command : javac -cp "libs/*" Main.java in the terminal. Make sure your present working directory is your project -folder itself.
Step 6: Run the Java program by using : java -cp ".;libs/*" Main command in terminal.
Output In Terminal:
Output for the code In terminalOutput In eclipse Editor:
Output of get Response status codeA browser also pops up opening the GFG website landing page. A successful response code is seen in output.
Conclusion
In summary, getting response status codes with Selenium WebDriver is essential for effective web testing and automation. Although Selenium WebDriver itself doesn't provide direct methods for retrieving HTTP response codes, you can utilize tools like BrowserMob Proxy or the Chrome DevTools Protocol to achieve this. BrowserMob Proxy offers a straightforward way to capture and analyze HTTP traffic, while the Chrome DevTools Protocol provides a more integrated approach for Chrome users. By incorporating these tools into your testing workflow, you can ensure that your web applications are functioning correctly and efficiently, providing valuable insights into server responses and performance.
Similar Reads
Wait Until Page Is Loaded With Selenium WebDriver For Python
Selenium is an automation tool or a web framework used mainly in testing web applications across various browsers. Apart from testing web applications, we can also perform various tasks with selenium. With the help of selenium, we can also perform various web related tasks such as web scraping, web
5 min read
How to check if an element exists with Selenium WebDriver?
Selenium is one of the most popular tools for automating web applications. Selenium is not a single tool but rather a set of tools that helps QA testers and developers to automate web applications. It is widely used to automate user interactions on a web page like filling out web forms, clicking on
7 min read
How to use xPath in Selenium WebDriver to grab SVG elements?
Selenium WebDriver is a powerful tool for automating web browsers to test the functionality of web applications. However, when working with SVG elements on a webpage, it can be tricky to locate and interact with them using standard locators like ID, class, or name. In such cases, XPath comes to the
2 min read
How to send a report through email using Selenium Webdriver?
In the world of automation testing, generating and sharing test reports is crucial. After executing tests using Selenium WebDriver, it's often necessary to share the results with team members or stakeholders. Automating the process of sending these reports via email can save time and ensure that eve
4 min read
Junit Test with Selenium WebDriver
Selenium is a browser automation tool that is used for testing purposes while Junit is a unit testing framework and by integrating them both we can write an automation test that will give the direct result of assertions. Junit is used with Java applications and Java also supports Selenium thus, we c
8 min read
How do I set the Selenium webdriver get timeout using Java?
Setting timeouts is important for good automated testing in Selenium WebDriver. One important timeout is page load timeout. This controls how long Selenium waits to load a page when visiting a given URL. If there is no timeout, tests may be stuck when pages load slowly. This results in failed tests.
2 min read
How to start with Selenium Debugging?
Debugging is essential for any developer, especially when working with Selenium for test automation. As your test scripts grow in complexity, the chances of encountering unexpected issues increase. Selenium debugging allows you to identify and resolve these issues by systematically analyzing your co
6 min read
How to hide Firefox window (Selenium WebDriver)?
In situations where you might wish to execute tests without a visible browser window, while automating web tests with Selenium WebDriver; it is possible for one to run headless browsers for example which will help save resources and speed up the execution of these tests. This article will cover how
3 min read
How to get text from the alert box in java Selenium Webdriver?
In Automation testing, we can capture the text from the alert message in Selenium WebDriver with the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the WebDriver focus from the main page to the alert
2 min read
Handle Firefox Not Responding While Using Selenium WebDriver using java?
During the usage of Selenium WebDriver with Java and internet applications, the problem of having a âFirefox Not Respondingâ error may be quite frequent when running lengthy or detailed tests. This problem tends to interfere with test flows and thus fails in test cases and returns wrong results. To
3 min read