[2023 The most complete and most popular on the entire network] Selenium WebDriver tutorial (recommended collection)

In this tutorial, I will introduce you to Selenium Webdriver, which is the most widely used automation testing framework in the market today. It is open source and works with all famous programming languages ​​like Java, Python, C#, Ruby, Perl, etc. to automate browser activities. In this article, I'll tell you everything you need to know to start testing web applications with Selenium WebDriver.

The following are the topics of this tutorial:

  • What is Selenium Webdriver?
  • Is Selenium easy to learn?
  • What does Selenium software do?
  • What are the basics of Selenium?
  • Disadvantages of Selenium RC and the birth of WebDriver
  • What are browser elements?
  • Locate browser elements on web pages
  • Operations on browser elements

What is Selenium WebDriver?

Selenium WebDriver is a web-based automated testing framework that can test web pages launched on various web browsers and various operating systems. In fact, you are also free to write test scripts in a variety of programming languages ​​such as Java, Perl, Python, Ruby, C#, PHP, and JavaScript. Please note that Mozilla Firefox is the default browser for Selenium WebDriver.

But many times, new testers will think of this question:

Is Selenium easy to learn?

To answer this question in layman's terms, I would say: "Yes, it is!". Selenium is really easy to learn and master as you only need a basic understanding of any common programming language (e.g. Java, C#, Python, Perl, Ruby, PHP). Prior knowledge of any of these programming languages ​​can be helpful in writing test cases. But if you don't have one, then don't worry. Selenium IDE is a GUI-based tool that can be used effectively.

What does Selenium software do?

Here are some of the most attractive uses of Selenium software:

  1. Automated Testing: Automated testing comes in handy in large projects where, if not for Selenium, testers would have to manually test every feature created. With Selenium, all manual tasks can be automated, reducing the burden and stress on testers.
  2. Cross-browser compatibility: Selenium supports multiple browsers such as: Chrome, Mozilla Firefox, Internet Explorer, Safari and Opera.
  3. Improve test coverage: Through automated testing, the overall testing time can be reduced, thereby freeing up time for testers to perform more tests under different test scenarios at the same time.
  4. Reduced test execution time: Since Selenium supports parallel test execution, parallel test execution time can be significantly reduced.
  5. Multi-operating system support: Selenium WebDriver provides support across multiple operating systems such as Windows, Linux, UNIX, and Mac. Using Selenium WebDriver, you can create test cases on Windows operating systems and execute them on Mac operating systems.

What are the basics of Selenium?

WebDriver is part of Selenium v2.0. Selenium v1 only consists of IDE, RC and Grid. But the major breakthrough of the Selenium project was the development and introduction of WebDriver as a replacement for Selenium v2. However, with the release of Selenium v3, RC is deprecated and migrated to legacy packages. You can still download and use the RC, but don't expect any support for it.

In short, the advantages of WebDriver over RC are:

  • Supports more programming languages, operating systems and web browsers
  • Overcome Selenium 1 limitations such as file uploads, downloads, pop-ups, and conversation barriers
  • Compared with RC, the commands are simpler and the API is better
  • Supports batch testing, cross-browser testing and data-driven testing

However, the disadvantage compared to RC is that test reports cannot be generated. RC generates detailed reports.

The following diagram describes how WebDriver works:

But have you ever wondered why you need Selenium Webdriver? Next, I'll discuss the limitations of Selenium RC, since this is the reason why WebDriver was ultimately developed.

现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:110685036

 

Disadvantages of Selenium RC and the birth of WebDriver

You might be surprised when I say that Selenium RC was an instant hit when it was launched. That's because it overcomes the Same Origin Policy issue, which is a major issue when testing web applications using Selenium Core. But do you know what a Same Origin Policy issue is?

Same-origin policy is a rule used to enforce the security model of web applications. Under the Same Origin Policy, web browsers will allow JavaScript code to access elements on a web page if and only if the JavaScript being tested and the web page originate from the same domain. Selenium Core is a JavaScript-based testing tool that is limited by its inability to test every web page.

But when Selenium RC came along, it freed testers from the same origin policy issue. But how does RC do this? RC does this by using another component called Selenium RC Server. Therefore, RC is a tool composed of two components: Selenium RC server and Selenium RC client .

Selenium RC Server is an HTTP proxy server designed to "trick" the browser into believing that Selenium Core and the web application under test are from the same domain. Therefore, JavaScript code cannot be blocked from accessing and testing any website.

Despite Selenium RC's popularity, it has its own problems. The main thing is the time it takes to execute the tests. Because the Selenium RC server is the middleman between the browser and your Selenium commands, executing the tests is very time-consuming. In addition to the time factor, the architecture of RC is also somewhat complex.

This architecture involves first injecting Selenium Core into the web browser. Selenium Core will then receive the instructions from the RC server and convert them into JavaScript commands. This JavaScript code is responsible for accessing and testing web elements. The picture below will help you understand how RC works.

To overcome these problems, Selenium WebDriver was developed. WebDriver is faster because it interacts directly with the browser and does not require an external proxy server. The architecture is also simpler since the browser is controlled from the operating system level. The following diagram will help you understand how WebDriver works.

Another benefit of WebDriver is that it supports testing on the HTML Unit driver (headless driver). When we say headless driver, it refers to the fact that the browser does not have a GUI. On the other hand, RC does not support the HTML Unit driver. These are the reasons why WebDriver scores higher than RC.

Before learning the concepts of Selenium, you should have a basic understanding of Java or any other object-oriented programming language. Selenium supported languages ​​include C#, Java, Perl, PHP, Python and Ruby. Currently, Selenium Webdriver is most popular in Java and C#.

Now, let's move on and in the next part learn about "Browser Elements", I will tell you what these elements are and how to test on these web elements.

What are browser elements?

Elements are the different components present on a web page. The most common elements we noticed while browsing were:

  • text box
  • CTA button
  • image
  • Hyperlink
  • radio button/checkbox
  • Text area/error message
  • Drop-down box/list box/combo box
  • Web forms/HTML forms
  • frame

Testing these elements essentially means that we have to check that they work properly and respond the way we want them to. For example, if we are testing a text box, what would you test it for?

  1. Are we able to send text or numbers to a textbox
  2. Can we retrieve text that has been passed to a textbox etc?

If we are testing images, we may need:

  1. Download pictures
  2. upload image
  3. Click on image link
  4. Retrieve image titles and more.

Similarly, operations can be performed on each of the previously mentioned elements. But only after the element is placed on the web page can we perform actions and start testing it, right? Therefore, the next topic, I will introduce element locator technology.

Locate browser elements present on a web page

Every element on a web page has attributes. Elements can have multiple attributes, and most of these attributes are unique to different elements. For example, consider a page with two elements: an image and a text box. Both elements have a "name" attribute and an "ID" attribute. These attribute values ​​must be unique for each element. In other words, two elements cannot have the same attribute value. The "class name" of elements can have the same value.

In this example, the image and textbox can neither have the same "ID" value nor the same "Name" value. However, a group of elements on a page may have some properties in common. I'll tell you later what these properties are, but before that, let me list 8 properties that we can use to locate elements. These properties are ID, name, class name, tag name, link text, partial link text, CSS and XPath.

Since elements are positioned using these properties, we call them "locators". The locators are:

  • By.id

Syntax: driver.findElement(By.id(“xxx”));

  • By.name

Syntax: driver.findElement(By.name(“xxx”));

  • By.className

Syntax: driver.findElement(By.className(“xxx”));

  • By.tagName

Syntax: driver.findElement(By.tagName(“xxx”));

  • By.linkText

Syntax: driver.findElement(By.linkText(“xxx”));

  • By.partialLinkText

Syntax: driver.findElement(By.partialLinkText(“xxx”));

  • By.css

Syntax: driver.findElement(By.css(“xxx”));

  • By.xpath

Syntax: driver.findElement(By.xpath(“xxx”));

By looking at the syntax above, you may have realized that the locator is called internally. Therefore, before proceeding further, you need to learn all the other methods, browser commands, and functions you can use to perform operations on elements.

Operations on browser elements

From now on, you'll have a lot of fun with less theory and more code. So, get ready, open the Eclipse IDE, and install the necessary Selenium packages.

To start testing a web page we need to first open the browser and then navigate to the web page by providing the correct URL? Take a look at the code below, I copied the same code above. The Firefox browser will launch first and then navigate to the Facebook login page.

package seleniumWebDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebDriverClass
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.gecko.driver", "files/geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.facebook.com/");
        driver.getTitle();
        driver.quit();
    }
}

import
org.openqa.selenium.WebDriver; is a library package that contains the classes required to launch a browser with a specific driver loaded.

import
org.openqa.selenium.firefox.FirefoxDriver; is a library package that contains the FirefoxDriver class, which is required to launch browsers that launch FirefoxDriver as the WebDriver class.

System.setProperty(“webdriver.gecko.driver”, “files/geckodriver.exe”); – This command notifies the runtime engine that the Gecko driver exists in the specified path. After Firefox 35, we need to download the Gecko driver to use WebDriver. If you want to test on Chrome, you have to download ChromeDriver (which is an .exe file) and specify its path in this line of code. We have to do the same for other browsers.

WebDriver driver = new FirefoxDriver(); – This command starts a new Firefox driver object.

driver.get(“ https://www.edureka.co/ ”); – This method is used to open the specified URL.

driver.getTitle(); – This command gets the title of the currently open tab in the browser.

driver.quit(); – This command closes the browser driver.

But what if you want to navigate to a different URL and then test? In this case, you can use the navigation.to() command as shown in the following code snippet. Then, if you want to go back to the previous page, you can do it by using the navigation.back() command. Similarly, to refresh the current page, you can use the navigation.refresh() command.

driver.navigate().to(“https://www.edureka.co/testing-with-selenium-webdriver”);
driver.navigate().refresh();
driver.navigate().back();

If you want to maximize the size of your browser window, you can do so using the code snippet below.

driver.manage().window().maximize();

If you want to set custom dimensions for your browser window, you can set your own dimensions, as shown in the code snippet below.

Dimension d = new Dimension(420,600);
driver.manage().window().setSize(d);

Now that you know most of the basics, let's move on to the next topic. Let's try to find an element on a web page and perform all possible operations.

I'm pretty sure that all of you have Facebook accounts. So let me show you how to log in to Facebook bypassing the credentials from the code itself.

There are two text fields in the login page, one for email/phone and another for password . We have to find these two elements, pass the credentials to these elements, and then find the third element: the " Login " button that needs to be clicked.

Please see the screenshot below. This is a screenshot of the Facebook login page.

If you inspect (Ctlr + Shift + i) this page, you will see the same window in your browser. Then, under Elements , a list of all elements present on the page and their attributes will appear. There are three sections highlighted in the screenshot above. The first highlighted element is the email text field, the second is the password text field, and the third is the "Login" button.

If you remember, I mentioned earlier that you can use element locator techniques to locate these elements. Let's use it to locate these elements and send field values.

This is the syntax for finding elements: driver.findElement(By.id(“xxx”));

In order to send its value we can use the method sendKeys(" credentials ");

To click a button we have to use click();

So, let's start finding elements and operating on them. The code for this is in the code snippet below.

driver.findElement(By.name("email")).sendKeys("[email protected]");
driver.findElement(By.name("pass")).sendKeys("xxxxxx");
driver.findElement(By.id("u_0_q")).click();

In line 1, we identify the Email element by its unique "name" attribute and send it to EmailID.

In line 2, we identify the Password element by its unique "name" attribute and send it the password.

In line 3, we find the "Login" button element by its unique ID and click the button.

Simply adding these lines of code may not be enough. That's because of the dynamic nature of the page, it may not respond immediately, and while the page is loading, WebDriver will terminate and throw a timeout exception error. This issue may not happen on Facebook pages anytime soon, but it will most likely happen on any other e-commerce website and other dynamic websites.

To overcome this problem, we need to use an advanced technology. We need to ask our WebDriver to wait after the page has been accessed and the page has fully loaded, we need to find the element and then perform the action.

If you want your WebDriver to wait until all elements are loaded into the web page and then close the browser, then we can use the driver.wait() method or the Threads.sleep() method to achieve this. However, if you are writing more advanced code, then you should use implicit wait or explicit wait . But for our case the following command is enough.

driver.wait(5000);
// or use this:-
Thread.sleep(5000);

However, when using wait conditions, remember to import this library:

import java.util.concurrent.TimeUnit;

We do this because wait classes and their associated methods will be present in this library.

Below is the complete code snippet of the code I explained.

package seleniumWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;

public class WebDriverClass
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.gecko.driver", "files/geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.facebook.com/");
        driver.manage().window().maximize();
        driver.getTitle();
        driver.navigate().to(“https://www.edureka.co/testing-with-selenium-webdriver”);

        driver.navigate().back();
        driver.navigate().refresh();
        driver.wait(5000);
        // or use
        // Thread.sleep(5000);

        driver.findElement(By.name("email")).sendKeys("[email protected]");
        driver.findElement(By.name("pass")).sendKeys("xxxxxx");
        driver.findElement(By.id("u_0_q")).click();

        driver.quit();
    }
}

When you replace your credentials with your actual email and password and execute this code, Facebook will open in a new window, enter your credentials and log in to your account.

Look ! You have successfully logged in, which means your complete code has been fully executed.

I used the ID and Name attributes to locate the element. In fact, you can use any other locator to find elements. XPath is the most useful and important locator technology. But as long as you can find even one of these properties and use it to position the element, you'll be fine.

Finally, I would like to thank everyone who read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.
 

Insert image description here

Guess you like

Origin blog.csdn.net/jiangjunsss/article/details/133149183