Selenium Article Series - 5 - Browser Commands
Kaan Denizay
Yaz?l?m Test Otomasyon Mühendisi @ Pera | ISTQB? CTFL | Test Automation, Selenium, JIRA
-Oh, look! A star has fallen! Let's make a wish!
-Actually, there is no such thing as a shooting star, Olric. It is just a meteorite that leaves a trace as a result of burning as it passes through the atmosphere at a very high speed.
-I wonder, if you are the holiday of the most beautiful moments, my colonel? ??
(In Turkish, the "tatil" word means holiday and stopping something. Also, the "katil" word means murderer. There is a rhyme between these words)
-Holiday? Isn't it something else?
-I say holiday, when you look at it etymologically, this sentence has a meaning close to the word you think of.
-Oh Olric, what will happen to your love for these words? I'm sorry for interrupting this beautiful moment. If you want to forgive me for my fault, let's play a game before class. I'm starting with the word, I wish for the most:
-Peace
-Tranquility
-Love
-Respect
-Book
-Pen
-Science
-Art
-Forest
-Sea
(All these words have five letters in Turkish)
-Okay, the game is completed. Both sides drew by producing a sufficient number of words that met the necessary conditions. The winner of this game, which would have no winner even if it was prolonged, was friendship, as usual, and since there was no loser, it was condemned by the members of the Club of Those Who Do Not Have Enough Words and Emotions with a declaration written in the language of "No -ish".
We can move on to our lesson!
In our previous lesson, we learned how to write our first Selenium codes on the browser and thus entered Selenium codewise. In this lesson, we will discuss browser commands that use the WebDriver interface. Some of these commands were introduced in the previous lesson. In this lesson, we will focus on the methods marked in the below screenshot that are utilized to perform operations on the browser itself.
To begin, it's important to note that the methods outside of the area depicted in the image belong to the Object class. These are general methods that are not specific to the WebDriver interface and can be accessed easily by an object created in any class. On the other hand, the findElement() and findElements() methods located within the drawn area are commonly used in Selenium tests. These methods are used to locate web elements on the browser and contain many details. Therefore, we will discuss their use in detail in our upcoming lessons. Similarly, the getWindowHandle/s() and switchTo() methods are used to manage the windows and tabs run by the driver object. We will explore this in more depth as we become more proficient in Selenium. Since we are currently working on a single window and tab, we do not need to use these methods. Additionally, I will explain the manage() method, which allows us to use the methods of the Options interface as needed. We utilized this method in our last lesson to change the size of the web browser to full screen. Now, let's discuss each of the other methods individually.
get() method
In our last article, we stated that the get() method is used to direct the browser to a certain page.
driver.get("https://the-internet.herokuapp.com");
In Java, the values written in parentheses of the defined methods represent the parameters of that method. The "get()" method in Selenium (Selenium WebDriver) accepts a string type and only one parameter. It uses this parameter to load the relevant page on the running browser. This method does not return any value after loading the page due to its void return type. It is interesting to note that, in general programming logic, "get()" methods are written to get a value, call it somewhere, and use it. Therefore, in many cases, these methods return a value. Anyway, let's continue our topic after offering my small criticism. ??
navigate().to() method
"Oh, Eureka!" This is exactly what a method should be like, my friend. When the name of a method itself is self-explanatory, it's a great indicator of clean code. This new method has the same functionality as the old get() method. But, the difference is that it can accept both string and URL types of parameters (separately, not simultaneously). However, let me point out that the use of get() method is more common. Below, I am sharing both ways of using it. If you want to use URL as a parameter, you need to comment on the top single line, and uncomment the next two lines below it.
driver.navigate().to("https://the-internet.herokuapp.com");
// URL url = new URL("https://the-internet.herokuapp.com");
// driver.navigate().to(url);
getTitle() method
This method returns the title of the current page. The title value is actually the value displayed in the tab section.
Each page in the image has a value shown in the tab section. getTitle() method returns the value written here as a string. The sent value is either kept in a variable or can be used directly as a parameter in a different method. In our code, we used the value from this method as a string parameter directly in the println() method. Instead, we could create a new string variable and store the value we received in this variable, but this would cause unnecessary RAM usage. If we do not need to store the value sent by the method and use it in more than one place, we can present it as a parameter directly into a different method, as we use here. Finally, let us point out that this method does not take any parameters.
System.out.println(driver.getTitle());
// String pageTitle = driver.getTitle();
// System.out.println(pageTitle);
getCurrentUrl() method
This method returns the string value of the current webpage's address on the browser. It does not require any parameters. To print this URL value to the console, we can use the following code, which is similar to the code used for the getTitle() method:
System.out.println(driver.getCurrentUrl());
getPageSource() method
This method is used to get the source of the current page. The page source is an HTML document that contains all the HTML structures that make up the page. You can also access this document via the browser. This method is generally used to check whether an object exists on the page and thus take the necessary action regarding the test. This action may be a requirement such as continuing the test if any word or text is present on the page and stopping the test if it is not.
System.out.println(driver.getPageSource());
quit() and close() methods
In our previous article, we discussed two methods: close() and quit(). While close() only closes the currently active window that is being controlled by the driver object, quit() terminates all windows and tabs that are being run by that object. Neither method requires any parameters and both methods do not return any values. In case multiple driver objects are created by Selenium, these methods only terminate the window of the driver object where they are called. Other driver objects remain unaffected. To conclude, let's discuss navigate() methods and wrap up today's topic.
Browser Navigation Commands
Navigation commands are functions called by the driver.navigate() method. The driver.navigate().to() method we just mentioned is one of them. The others are forward(), back() and refresh() methods listed in the image below.
navigate().forward(), navigate().back(), and navigate.refresh() methods
These methods function the same as the forward-backward and refresh buttons you see on the browser.
If you navigate away from the first page and wish to return to it later, you can use the back() method. Conversely, if you want to go back to the newly opened page, you can utilize the forward() method.
领英推荐
To demonstrate the use of these methods, let's click on a simple link to move to a new page. After a brief period, we'll return to the initial page and wait again before revisiting the second page.
To click on the "A/B Testing" link visible on the page, we need to use a locator that identifies this element. I'll explain this topic in further detail in our next article. For now, let's assume that we'll use the link text visible on the screen to locate this element.
We will first mark the link using the method below, and then we will click on the web element we marked using the click() method.
driver.findElement(By.linkText("A/B Testing")).click();
After clicking on this link, Selenium directs us to the page in the link, just like a real user clicks any button on the page and is directed to the relevant page.
Once we have navigated to a webpage, we can use the back() and forward() commands of Selenium to move back and forth between pages. However, since Selenium executes these commands very quickly, it can be hard to notice any changes during the current test run. To address this issue, we can make the code wait for 2 seconds before executing any back-forward operations. While there are more efficient wait methods available in Selenium, the approach I am currently using is the simplest one. We will explore these more advanced wait methods in the future.
Thread.sleep(2500);
When we write code in IntelliJ, it may show an error message due to the use of the sleep() method. In some cases, this method may cause an error that needs to be handled properly, otherwise, the application crashes and stops working. Fortunately, many smart editors, including IntelliJ, provide us with warnings to manage these errors. To fix this issue, we need to add the relevant part to the main() method by clicking on the marked area in the image.
After these steps, the error message will disappear. Now, after the waiting period is completed, let's go to the previous page and wait for a while:
driver.navigate().back();
Thread.sleep(2500);
Let's go to the next page again and refresh the page after waiting for a while:
driver.navigate().forward();
Thread.sleep(2000);
driver.navigate().refresh();
Finally, let's close all windows run by the driver object:
driver.quit();
In the last case, our entire code is as follows:
The expected output of the code is displayed in the console area as follows. I'd like to mention that I have commented out the getPageSource() method to limit the output. However, if you want to view the complete page source, you can activate this line again.
After successfully running our code, we will see the message "Process finished with exit code 0" in the console. However, if an error occurs during the execution of our code, we will see an error message indicating the location and cause of the error. In such cases, we must fix the error and then run the code again.
Debugging is an essential part of programming, as errors can happen due to various reasons. Even experienced software developers cannot write error-free code in one attempt, especially in large-scale programs. Therefore, we need to approach error messages with an analytical mindset and solve the underlying problems to ensure our code runs smoothly.
The image displayed above highlights an error encountered during the execution of the program. I intentionally altered a section of the code to trigger the error. If you carefully examine the error message, you can identify the cause of the error and the exact line in the code where it occurred.
The error message indicates that there is an issue with the code on line 33. This is because the web element we defined in the method cannot be located on the relevant webpage. Upon reviewing the code, we notice that the link text "A/B Testing123" is being used, which does not exist on the relevant page. As a result, an error is thrown as the element cannot be located. To resolve this issue, we need to update our code with the correct link text and rerun it. Once done, we should be able to execute the code without encountering any errors in this line.
driver.findElement(By.linkText("A/B Testing")).click();
-Yes, Olric, we have completed our lesson today. Now let's continue our conversation.
-Although the stars are spherical, why do we symbolize them as 5-pointed, my colonel?
-You always ask difficult questions, Olric! However, as far as I have researched, this is because light moves as a wave as well as a particle, and these waves bend when they encounter an object. However, the structure of our eye lenses causes us to perceive these objects as having five corners.
-What about the golden ratio? In addition to the ordinary numbers 1 and 2, the number 5 is included in the root and reveals that magnificent ratio. So much so that, this ratio even determines our perception of aesthetics and beauty, my colonel.
-Yes, Olric. The golden ratio is one of the most important constants symbolizing the magnificent balance in nature. We cannot thank the science of mathematics enough for allowing us to decipher this language! The language of nature is mathematics, Olric, and it is not possible to describe the pleasure experienced by a mathematician who discovered this aesthetic.
-Yes, my colonel. We always talked about the number 5 today, but now our audience should know why. Today was our 5th issue, this is the reason for this special fiction and eulogy for the number 5.
- If we did this to number 5, how would we explain the 6th issue, Olric?
See you in our next lesson, stay safe!
References