课程: Test Automation with Selenium WebDriver for Java

Intro to WebDriver

- [Instructor] Selenium WebDriver is a popular open source tool for automating web browser interactions. It's commonly used to automate UI testing and supports all modern browsers. In this course, we'll use Chrome, but the scripts we write can be executed on any supported browser. To do so, we'll need to use the WebDriver class, which acts as an interface for controlling and interacting with web browsers. It allows us to programmatically open, navigate, and manipulate webpages just like a real user would. Let's create a simple Java program that sets up Selenium WebDriver with Chrome, opens a website, and then closes the browser. We'll begin by declaring a WebDriver object. We can do so by saying static protected WebDriver, and we'll call this object driver. The WebDriver interacts with browsers through browser-specific executables. For Chrome, this is the Chrome driver executable. We can automatically download and configure the browser by saying chromedriver, and we'll put parentheses and then say .setup. Next, we can customize the behavior and properties of the browser instance by first instantiating a class called Chrome Options. So we'll say var options = new ChromeOptions. By setting specific options, we can control how the browser behaves when executing our scripts. For example, because we are using a codespaces container, we must set the no-sandbox option to prevent any complications. We do this by saying options.addArguments, and inside of parentheses, in quotation marks, we'll say --no-sandbox. Great, now we can initialize our WebDriver object with the Chrome driver class and pass in our options. To do so, we'll say driver = new ChromeDriver, and then we'll pass in the options. This will open a new Chrome browser window configured with the options we specified. Once the browser is open, we can navigate to any webpage by calling driver.get. And inside of here, we'll pass in the URL of the webpage as a string. So you can say https://google.com. If you were to run this script outside of the codespaces container environment, the browser would automatically open on your desktop. However, in this environment, to see the browser, we'll need to go to the Ports tab, hover over the Forwarded Addresses that correspond to the Port 6080. Click the globe icon to open a browser in a new tab, and then on this tab you'll see noVNC. Click the Connect button. Now, within codespaces, we can run our script by clicking the Run label above the main method. Switching over to our virtual desktop, we see Selenium WebDriver open a browser and navigate to google.com. It's a good practice to programmatically close the browser after your script is done. You can do so with the driver.quit command. This not only closes the browser, but it also shuts down the WebDriver instance, ensuring that all associated processes are properly terminated.

内容