This article is probably the most complete selenium (Java version) hands-on article available, but it is not one of them. If you are a Java developer, this article will help you quickly build the entire Selenium automated testing framework so that you can help your company upgrade to an automated testing architecture. If you are a tester, then you should follow this article to practice, encountered with a consulting company Java development, you can also complete the automation test architecture upgrade. Of course, if your company is already automated testing, this article is just a refresher.Copy the code
preface
When you think of automated testing Selenium, everyone thinks of scripting in Python. But we chose the Java language because I believe most companies have far more Java programmers than Python. Many testers, on the other hand, are not proficient in the programming language, so they need guidance. Instead of using the simpler Python language and not being able to read the syntax and not be helped; Instead, use the Java language, where you can quickly get help from Java developers on both syntax and programming ideas.
background
Many companies may have standard back-end unit test code, but the automation test needs to test the entire system, the front end is directly shown to the user, so the front end is particularly important, this article is based on h5 web front-end automation test. Of course, it is recommended to separate the front and back ends of the project, if the project does not have the front and back end separation can refer to a small company RESTful, shared interface, front and back end separation, interface convention practice.
At present, there are few complete articles on Selenium on the Internet, and it is difficult to buy a book dedicated to Selenium, which has left many testers at a loss to start with. This article will remedy this problem by covering the practice of Selenium in as much detail as possible. Provide a simple version of the full project code on Github (because the company’s project code is not desensitized, it cannot be directly put on Github).
The relevant knowledge
- HTML tags
- CSS styles
- Js based
- Java based
- Bat Script Basics
First, the HTML consists of the tag
Formal practice
Install Firefox
Since Selenium can automatically record scripts in the Firefox browser, we can generate scripts in different languages by recording scripts, which saves us 90% of the scripting workload. You can install the latest version of Firefox, Then install Katalon Recorder (Selenium IDE for Firefox) Using firefox browser open https://addons.mozilla.org/zh-CN/firefox/addon/katalon-automation-record/?src=search
Recording script
Take Baidu search nuggets as an example
- The address bar opens Baidu
- In the upper right corner, open the Katalon extension
- Click on Katalon’s New
- Click on the Record
- Enter gold digger in web page
- Open the first nuggets website
- Check out an article I wrote on the Nuggets website about how I rethought the entire development program to help automate DevOps.
- Click # 1. How can I refactor the entire r&d project to facilitate automated DevOps?
- Click on Katalon’s Stop
Each operation is prompted in the lower right corner
Run and analyze the script
After recording, we click Play and see that Firefox automatically completes what we just did (turn off popover blocking, or add Denver and Baidu to the list of unblocked popovers).
Click on the Export
You can see the various languages C#, Java, katalon, python2, and so on. Let’s look at the Python2 script first
# -*- coding: utf-8 -*-from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re class Test(unittest.TestCase): defsetUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_(self):
driver = self.driver
driver.get("https://www.baidu.com/index.php?tn=monline_3_dg")
driver.find_element_by_id("kw").click()
driver.find_element_by_id("kw").clear()
driver.find_element_by_id("kw").send_keys(u"Gold net")
driver.find_element_by_xpath("//div[@id='container']/div[2]/div").click()
driver.find_element_by_link_text(u"Nuggets - Juejin. Im - a community to help developers grow").click()
# ERROR: Caught exception [ERROR: Unsupported command [selectWindow | win_ser_1 | ]]
driver.find_element_by_xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input").click()
driver.find_element_by_xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input").click()
driver.find_element_by_xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input").clear()
driver.find_element_by_xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input").send_keys(u"How can I refactor an entire r&d program to enable automated DevOps?")
driver.find_element_by_xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input").send_keys(Keys.ENTER)
driver.find_element_by_link_text(u"How can I refactor an entire r&d program to enable automated DevOps?").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
Copy the code
Let’s look at the Java junit scripts
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Test {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.katalon.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void test() throws Exception {
driver.get("https://www.baidu.com/index.php?tn=monline_3_dg");
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("Gold net");
driver.findElement(By.xpath("//div[@id='container']/div[2]/div")).click();
driver.findElement(By.linkText("Nuggets - Juejin. Im - a community to help developers grow")).click();
// ERROR: Caught exception [ERROR: Unsupported command [selectWindow | win_ser_1 | ]]
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).clear();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys("How can I refactor an entire r&d program to enable automated DevOps?");
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("How can I refactor an entire r&d program to enable automated DevOps?")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true; }}}Copy the code
The amount of detail in Python is a little less than in Java, but this article is about Java language practice.
We’ll focus on the Test method in the Java version of the @test annotation
driver.get("https://www.baidu.com/index.php?tn=monline_3_dg");
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("Gold net");
driver.findElement(By.xpath("//div[@id='container']/div[2]/div")).click();
driver.findElement(By.linkText("Nuggets - Juejin. Im - a community to help developers grow")).click();
// ERROR: Caught exception [ERROR: Unsupported command [selectWindow | win_ser_1 | ]]
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).clear();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys("How can I refactor an entire r&d program to enable automated DevOps?");
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("How can I refactor an entire r&d program to enable automated DevOps?")).click();
Copy the code
Probably a lot of people can see it already
driver.get(“https://www.baidu.com/index.php?tn=monline_3_dg”);
Open the baidu
driver.findElement(By.id(“kw”)).click();
Navigate to the HTML tag by id, and click click(); Clear the textbox. Clear (); SendKeys (” Dig “);
Here we take a look at baidu’s search box code
<input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">
Copy the code
Driver.findelement (by.linktext (” Nuggets – Juejin. Im – a community to help developers grow “)).click();
Click on the Nugget to navigate to the tag via LinkText and click.
After the div=juejin layer by layer positioning to the input, finally click to enter the article.
Understanding HTML Tags
HTML <input>
The label
The tag is used to collect user information. The input field can take many forms depending on the value of the Type attribute. Input fields can be text fields, check boxes, masked text controls, radio buttons, buttons, and so on.
<form action="form_action.asp" method="get">
First name: <input type="text" name="fname" />
Last name: <input type="text" name="lname" />
<input type="submit" value="Submit" />
</form>
Copy the code
Details refer to http://www.w3school.com.cn/tags/tag_input.asp
HTML <a>
The label
The <a> tag defines hyperlinks that are used to link from one page to another. The most important attribute of the <a> element is the href attribute, which indicates the target of the link.Copy the code
Details refer to http://www.w3school.com.cn/tags/tag_a.asp
HTML <div>
The label
<div style="color:#00FF00">
<h3>This is a header</h3>
<p>This is a paragraph.</p>
</div>
Copy the code
Details refer to http://www.w3school.com.cn/tags/tag_div.asp
…………………
Other labels are not a description, can be seen on the reference site meaning
Know CSS
There’s only one key one here, for example
<div class="css1 css2"> ********</div>
Copy the code
Indicates that the DIV uses both CSS1 and CSS2 styles, just know that if you can’t position the div on Selenium, you can use the CSS name to position it.
If you are interested, take a look at other CSS related knowledge.
Js based
There are two key points here
<a onclick="test()">test</a>
Copy the code
In the above code, clicking the A tag executes the test method in JS. When Selenium cannot locate the A tag, the test() method can be called directly.
You can write a simple JS script, popover code:
alert("hello");
Copy the code
Download Google Chrome
Download Google Browser, where version 63.0.3239.84 is available. For now, Google chrome version compatibility is good.
Download the selenium driver
https://www.seleniumhq.org/download/
However, this article is included in the Github project
Download the selenium webdriver
https://npm.taobao.org/mirrors/chromedriver/ to download and Google browser version 2.40 can not bottom, the paper making contained in the project
Download the idea development tool
https://www.jetbrains.com/idea/
This is complicated and is recommended under the guidance of a Java developer.
selenium
This version is easy, but sufficient
The final result
We recorded selenium scripts, edited them, and submitted them to git library, and Jenkins automatically compiled the JAR package, which was executed on any PC by bat command (by default, all modules were automatically executed after the developer submitted the code). Generate test reports according to functional modules and test items. For modules that failed the test
maximize
driver.manage().window().maximize();
Copy the code
Open the page
driver.get("https://www.baidu.com");
Copy the code
Positioning elements
WebElement element = driver.findElement(*);
Copy the code
When returning more than one:
List<WebElement> elements = driver.findElements(*);
Copy the code
Locating element mode
<input class="input_class input_class2" type="text" name="user-name" id="user-id" />
Copy the code
Locate by ID
WebElement element = driver.findElement(By.id("user-id"));
Copy the code
Locate by name
WebElement element = driver.findElement(By.name("user-name"));
Copy the code
Locate by className
WebElement element = driver.findElement(By.className("input_class.input_class2"));
Copy the code
Note that multiple classes are separated by decimal points and can also be located using cssSelector
WebElement element = driver.findElement(By.cssSelector("input"));
Copy the code
Locate via linkText, such as:
WebElement Element = driver.findelement (By. LinkText (" How do I refactor the entire r&d project to enable automated DevOps? ") ));Copy the code
It means link content positioning
PartialLinkText positioning, fuzzy content positioning, and similar
WebElement Element = driver.findelement (By. LinkText (" How do I refactor the whole r&d project? ") ));Copy the code
Locate by tagName
WebElement element = driver.findElement(By.tagName("form"));
Copy the code
Locating by xpath
WebElement element = driver.findElement(By.xpath("//input[@id='passwd-id']"));
Copy the code
The most complex and simplest version of this is
// Tag type [@attribute name = attribute value]Copy the code
But you can also locate the number
//input[4]
Copy the code
You can also add logical and or expressions to []
WebElement element = driver.findElement(By.xpath("//input[@type='text' and @name='user-name']"));
WebElement element = driver.findElement(By.xpath("//input[@type='text' or @name='user-name']"));
Copy the code
[] can also include start-with, ends-with, and contains, for example
WebElement element = driver.findElement(By.xpath("//input[start-with(@id,'user-')]"));
WebElement element = driver.findElement(By.xpath("//input[ends-with(@id,'user-')]"));
WebElement element = driver.findElement(By.xpath("//input[contains(@id,'user-')]"));
Copy the code
You can also have any property name
WebElement element = driver.findElement(By.xpath("//input[@*='user-name']"));
Copy the code
More xpath usage see http://www.w3school.com.cn/xpath/index.asp
Click on an element
.click()
Copy the code
Empty the input
.clear();
Copy the code
Input Indicates the input
.sendkeys (" nuggets ");Copy the code
If you want to upload attachments, sendKeys directly
.sendKeys("c:\shao.png");
Copy the code
Get the input
.getText();
Copy the code
A drop-down box
Select select = new Select(driver.findElement(By.id("frequency")));
select.selectByValue("1");
driver.findElement(By.id("validDays")).click();
Copy the code
select.selectByValue("a");
select.deselectAll();
select.deselectByValue("a");
select.deselectByVisibleText("");
select.getAllSelectedOptions();
select.getFirstSelectedOption();
Copy the code
Radio buttons
WebElement radio=driver.findElement(By.id("radio")); radio.click();         // Select an option radio.clear();         // Clear the option radio.isSelected();     // Check whether an option is selectedCopy the code
Check box
WebElement checkbox = driver.findElement(By.id("checkbox")); checkbox.clear(); // Clear the option checkbox.isSelected(); // Whether to selectCopy the code
Determine whether clickable
isEnabled()
Copy the code
The alert box operation
Alert alert = driver.switchTo().alert(); alert.accept();     / / determine alert. Dismiss ();   / / cancelCopy the code
The iframe switch (Focus on)
It is possible that many old projects have iframe. When the script is recorded, it can be recorded normally, but when it can be executed, it cannot be executed. In this case, you need to switch iframe
driver.switchTo().defaultContent();   // Go back to the default page driver.switchto ().frame("leftFrame"); // Switch to an iframeCopy the code
Switch to iframe. When the iframe is complete, switch back to the default page.
driver.findElement(By.linkText("Import template")).click();
WebElement iframe = driver.findElement(By.id("layui-layer-iframe1"));
driver.switchTo().frame(iframe);
Thread.sleep(2000);
driver.findElement(By.linkText("Reference")).click();
driver.findElement(By.xpath("//button[@type='submit']")).click();
driver.findElement(By.xpath("(//button[@type='button'])[3]")).click();
Thread.sleep(1000);
driver.findElement(By.linkText("Students")).click();
Copy the code
The above is excerpted from the project code for reference only
Perform js
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("viewDetail('1f50555e409a4597a027ff415ce6c9b4','09','2018')");
Copy the code
Execute the internal viewDetail method
Delayed operation (important)
A lot of times we need a delay, so use it
Thread.sleep(1000); // The delay is 1000 millisecondsCopy the code
Many errors are caused by waiting time. Try adding a delay and maybe the problem will pass.
Project code
Let’s say we have multiple environments in our product, we define an environments array, (which prompts the user for input when -1), and we have multiple modules, (which prompts the user for input when -1). The end code looks like this, and when executed, the error report will be emailed to a specific mailbox or somewhere else.
Running effect diagram
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import webfunction.*;
import java.util.Scanner;
public class Main {
private static WebDriver driver;
private static String baseUrl;
private boolean acceptNextAlert = true; / * * * * * each environments/private static String [] environments = {"Environment 1"."The environment 2"."Environmental 3".4 "environment"."Environment 5".6 "environment"}; Private static StringBuffer verificationErrors = new StringBuffer(); /** * error log ** / Private static StringBuffer verificationErrors = new StringBuffer(); /** * Whether the system is in debug mode */ private static Boolean debug =false; /** * -1 indicates manual mode. Otherwise, the specified number is used. ** / Private static String environment ="1"; /** * -1 indicates manual mode. Otherwise, specify a number. ** / Private static String Methods ="1"; Public static void main(String[] args) throws Exception {// Reference system.setProperty ("webdriver.chrome.driver"."C:\\selenium\\chromedriver.exe"); String uname, upw; Scanner sc = new Scanner(System.in); System.out.println("Please select environment");
for (int i = 0; i < environments.length; i++) {
System.out.println(i + ":" + environments[i]);
}
if ("1".equals(environment)) {
environment = sc.next();
}
System.out.println("Please enter the features you want to test, separated by commas.");
if ("1".equals(methods)) {
methods = sc.next();
}
driver = new ChromeDriver();
System.out.println("You have chosen" + environments[Integer.valueOf(environment)]);
switch (environment) {
case "0":
baseUrl = "http://*.*.*.*/";
uname = "admin";
upw = "admin";
testManage(baseUrl, uname, upw, methods, driver);
break;
case "1":
baseUrl = "http://*.*.*.*/";
uname = "admin";
upw = "admin";
testManage(baseUrl, uname, upw, methods, driver);
break;
case "2": // etc...break;
}
}
private static void testManage(String url, String uname, String upw, String methods, WebDriver driver) throws InterruptedException {// Login to the management end first weblogin. WebLogin (driver, URL, uname, upw); String[] strArray = null; strArray = methods.split(",");
for (int i = 0; i < strArray.length; i++) {
switch (strArray[i]) {
case "0": try {/ / system basic management - user management - new users WebSystemManage addnewUser (driver, url); } catch (Exception e) { verificationErrors.append("System basic management - User management - Adding user error");
log(e);
}
break;
case "1": try {// system management - user management - editUser websystemmanage.edituser (driver, url); } catch (Exception e) { System.out.println("System basic management-user management-user editing error");
log(e);
}
break;
default:
break; } } report(verificationErrors); } private static void report(StringBuffer verificationErrors) {// Send emails} /** * Output logs based on debug variables * @param e */ private static voidlog(Exception e) {
if (debug) {
e.printStackTrace();
}
}
private static boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private static boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private static String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true; }}}Copy the code
Public static void main(String[] args) throws Exception {}; The specific code is as follows:
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; public class Main { private static WebDriver driver; Public static void main(String[] args) throws Exception {// Reference system.setProperty ("webdriver.chrome.driver"."C:\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); // The following is the script driver after Katalon Recorder recording."https://www.baidu.com/index.php?tn=monline_3_dg");
Thread.sleep(2000);
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("Gold net");
Thread.sleep(100);
driver.findElement(By.id("su")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[@id='container']/div[2]/div")).click();
driver.findElement(By.linkText("Nuggets - Juejin. Im - a community to help developers grow")).click();
Thread.sleep(3000);
// ERROR: Caught exception [ERROR: Unsupported command [selectWindow | win_ser_1 | ]]
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).clear();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys("How can I refactor an entire r&d program to enable automated DevOps?");
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys(Keys.ENTER);
Thread.sleep(2000);
driver.findElement(By.linkText("How can I refactor an entire r&d program to enable automated DevOps?")).click(); }}Copy the code
The script exported by Katalon Recorder is in the comments in the above code, but we have added some latency operations. Selenium latency has three types: normal sleep, display wait, and implicit wait. To make it a little more simple, use thread.sleep (*); Delay, for example open Baidu delay 2 seconds, input “nuggets net” delay 100 milliseconds, search delay 3 seconds …………
Unfortunately, our code is reporting an error:
ERROR: Caught exception [ERROR: Caught exception] ERROR: Caught exception [ERROR: Caught exception] Unsupported command [selectWindow | win_ser_1 |]] this line).
Set<String> windowHandles = driver.getWindowHandles();
String windowHandle = driver.getWindowHandle();
for (String handle : windowHandles) {
if(! handle.equals(driver.getWindowHandle())) { driver.switchTo().window(handle);break; }}Copy the code
Export script By xpath (” / / div [@ id = ‘juejin’] / div [2] / div/headers/div/nav/ul/li [2] / form/input “) this sentence is very complex, we try to simplify it.
<input data-v-5ce25e66="" maxlength="32" placeholder="Search for gold." class="search-input">
Copy the code
First, look for the search-input style to see if the page has only one search-input style.
So we’re going to
By xpath (" / / div [@ id = 'juejin'] / div [2] / div/headers/div/nav/ul/li [2] / form/input ") / / instead By the className (" search - input ")Copy the code
The final code
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.util.Set; public class Main { private static WebDriver driver; Public static void main(String[] args) throws Exception {// Reference system.setProperty ("webdriver.chrome.driver"."C:\\selenium\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.baidu.com/index.php?tn=monline_3_dg");
Thread.sleep(2000);
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("Gold net");
Thread.sleep(100);
driver.findElement(By.id("su")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[@id='container']/div[2]/div")).click();
driver.findElement(By.linkText("Nuggets - Juejin. Im - a community to help developers grow")).click();
Thread.sleep(7000);
Set<String> windowHandles = driver.getWindowHandles();
String windowHandle = driver.getWindowHandle();
for (String handle : windowHandles) {
if(! handle.equals(driver.getWindowHandle())) { driver.switchTo().window(handle);break;
}
}
// ERROR: Caught exception [ERROR: Unsupported command [selectWindow | win_ser_1 | ]]
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).click();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).clear();
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys("How can I refactor an entire r&d program to enable automated DevOps?");
driver.findElement(By.xpath("//div[@id='juejin']/div[2]/div/header/div/nav/ul/li[2]/form/input")).sendKeys(Keys.ENTER);
Thread.sleep(2000);
driver.findElement(By.linkText("How can I refactor an entire r&d program to enable automated DevOps?")).click(); }}Copy the code
Compile the package
C:\Users\Administrator>cd C:\selenium
C:\selenium>java -jar selenium2.jar
Copy the code
Can automatic operation, the Windows download other versions 2.40 https://npm.taobao.org/mirrors/chromedriver/2.40/
Github project running
https://github.com/qq273681448/selenium
In case any reader has not changed the Maven library image, I put the lib package in the project. Use idea directly to open, some configuration may need to change, can refer to
Write in the last
At this point, a base version of the Selenium framework is built, and you can then connect to the database and randomly pull accounts from the library for project testing. It can also cooperate with BAT scripts to realize automated testing and report generation.