Java+selenium makes web-side automated test code

This was written a long time ago, the code may look a bit messy, just take a look ()

After all, writing this in java is not mainstream.

You need to add two package dependencies to the maven file first

Selenium mirror address (https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java)

TestNG mirror address (https://mvnrepository.com/artifact/org.testng/testng)

The code in the figure is as follows:

//Currently using the version with the most users, not the latest version of selenium
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>
//Using the 6.8.8 version of TestNG
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.8.8</version>
    <scope>test</scope>
</dependency>
</dependencies>

Then put the browser driver such as Chrome driver Chromedriver.exe (remember to check what version your Google browser is when downloading, if the version does not match, it is not applicable), place it in the newly created directory in the src file drivers (D:\java + selenium\src\drivers\chromedriver.exe) and then introduce chromedriver into the file.

In fact, the code of this piece is self-study based on the online class of station b, so there are many comments and it looks messy

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

import java.nio.file.Path;
import java.nio.file.Paths;

public class test {
    public WebDriver webDriver;
    @Test
    public void openBaidu(){
    //Introduce Chromedriver
        Path p1= Paths.get("src","drivers","chromedriver.exe");
        System.setProperty("webdriver.chrome.driver",p1.toAbsolutePath().toString());
        //Create a browser instance
        webDriver=new ChromeDriver();
        
        //Open Baidu
        webDriver.get("https://www.baidu.com");
        // Locate Baidu's search box element, and input data (ID positioning) - unique
        //webDriver.findElement (By.id("kw")).sendKeys("Tencent Classroom");
        // Locate Baidu's search element, and input data (Name positioning) - it will be repeated
        //webDriver.findElement(By.name("wd")).sendKeys("Tencent Classroom");
        //Locate to Baidu's search element, and input data (tagName) - there will be multiple elements found - not recommended
        //webDriver.findElement(By,tagName("input")).sendKeys("Tencent Classroom");
        //Locate to Baidu's search box element, and input data (className positioning)
        //webDriver.findElement(By.className("s_ipt")).sendKeys("Tencent Classroom");
        //Compound class names not permitted -->The problem of compound class names (you can’t put in the matching class name, you can only put in the unique class name, otherwise you will find the wrong style)
        //webDriver.findElement(By.className("s_btn")).click();
        //Locate the "news" element, and click (LinkText location) --> full text of the hyperlink
        //webDriver.findElement(By.linkText("News")).click();
        // Locate the "news" element, and click (partialLinkText positioning) --> hyperlink partial text
        //webDriver.findElement(By.partialLinkText("News")).click();
        //cssSelector element positioning
        //(1) tagName positioning
        //webDriver. findElement(By. cssSelector("input"));
        //(2) id positioning (you need to add a "#" in front of the id as an identifier, for example: #id)
        //webDriver.findElement(By.cssSelector("#kw")).sentKeys("Tencent Classroom");
        //(3) Locating according to className (you need to add a "." before the style name, for example: .s_btn)
        //webDriver.findElement(By.cssSelement(.s_ipt)).sentKeys("Tencent Classroom");
        //webDriver.findElement(By.cssSelement(.bg.s_btn)).click();
        //Target to Baidu, you can use multiple styles according to cssSelector positioning, but you need to add .
        // css precise positioning
        //According to element attributes, attribute name = attribute value, id, class, etc. can be written in this form, single attribute: By.cssSelector("tag name [attribute name = attribute value]");
        //Such as: By.cssSelector("input[name='xxx']");
        //Multiple attributes
        //By.cssSelector("Tag name[attribute 1=attribute value][attribute 2=attribute value]");
        //Single attribute
        //webDriver.findElement(By.cssSelector("input[maxlength='255']")).sentKeys("Tencent Classroom");
        //Multiple attributes
        //webDriver.findElement(By.cssSelector("input[maxlength='255'][autocomplete='off']")).sentKeys("Tencent Classroom");
    }
}



//element operation API
// getTagName ()
// Get the tag name of the element

// getAttribute(attribute name)
// Get the element attribute value according to the attribute name

//getText()
//Get the text value of the current element

//isDisplayed()
// Check if the element is displayed

//WebDriver-related APIs
//get(String url)
//Access the specified url page

//getCurrentUrl()
//Get the url address of the current page

//getTitle()
// Get the title of the current page

//getPageSource()
//Get the source code of the current page

//quit()
//Close the driver object and all related windows

//close()
//Close the current window

//getWindowHandle()
//return the current page handle

//getWindowHandles()
//Return all the handles of the pages opened by the driver object, different pages have different handles

//manage()
//This method can get Optiona--browser menu operation object
driver. manage(). window()

//navigate object
//Navigation navigation=driver.navigate()
//Get the navigate object

//navigation.to(url)
//Access the specified url address

//navigation. refresh()
//Refresh the current page

//navigation.back()
//Browser fallback operation

//navigation. forward()
//Browser forward operation

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.nio.file.Path;
import java.nio.file.Paths;

public class test2 {
    private static void openChrome() {
        // open the browser
        Path p1 = Paths. get("src", "drivers", "chromeDriver.exe");
        System.setProperty("webdriver.chrome.driver", p1.toAbsolutePath().toString());
        //Create a browser instance
        chromeDriver = new ChromeDriver();
    }

    public static ChromeDriver chromeDriver;
    public static WebElement webElement2;

    public static void main(String[] args) throws test, InterruptedException {
        openChrome();
        // get(String url)
        //Access the specified ur1 page
        chromeDriver.get("https://www.baidu.com");
        // wait 3s
        //Thread. sleep(3000);
        //chromeDriver.findElement(By.id("kw")).clear();//Clear the elements in the input box whose id is kw
        WebElement webElement1 = chromeDriver.findElement(By.id("kw"));
        chromeDriver.findElement(By.id("kw")).sendKeys("Tencent Classroom");
        chromeDriver.findElement(By.id("su")).click();//Click the Baidu button
        // getTagName ()
        // Get the tag name of the element
        System.out.println("Get the tag name of the element: " + webElement1.getTagName());
        // getAttribute(attribute name)
        // Get the element attribute value according to the attribute name
        System.out.println("Get the current maxlength attribute:" + webElement1.getAttribute("maxlength"));
        webElement2 = chromeDriver.findElement(By.xpath("//a[text ()='Settings']"));
        //getText()
        //Get the text value of the current element
        System.out.println("Get the text value of the element: " + webElement2.getText());
        //isDisplayed()
        // Check if the element is displayed
        System.out.println("Whether the element is displayed" + webElement2.isDisplayed());
        // getCurrentUr1(
        // Get the ur1 address of the current page
        System.out.println("The current URI is: " + chromeDriver.getCurrentUrl());
        // getTitle()
        // Get the title of the current page
        System.out.println("The current title is: " + chromeDriver.getTitle());
        // getPageSource()
        // Get the source code of the current page
        //System,out,printIn("The source code of the current page is: " + chromeDriver,getPageSource());/ / quit ()
        // close the driver object and all associated windows
        //chromeDriver.quit();
        //close()
        // close the current window
        System.out.println("The handle before the new window opens: " + chromeDriver.getWindowHandle());
        System.out.println("All handles before the new window opens:" + chromeDriver.getWindowHandles());
        Thread. sleep(3000);
        chromeDriver.findElement(By.xpath("//a[text()='Weibo_Weibo']")).click();
        Thread. sleep(1000);
        System.out.println("The handle of the new window opened:" + chromeDriver.getWindowHandle());
        System.out.println("All handles after the new window is opened:" + chromeDriver.getWindowHandles());
        //navigation object
        WebDriver.Navigation navigation = chromeDriver.navigate();
        //Visit Jingdong
        navigation.to("https://www.jd.com");
        Thread. sleep(1000);
        //refresh page
        navigation. refresh();
        Thread. sleep(1000);
        //go back
        navigation.back();
        Thread. sleep(1000);
        //go ahead
        navigation. forward();
        
    }
}
/*Three major waits: hard wait, implicit wait, display wait
Hard wait: Thread.sleep(time) in milliseconds
Implicit wait: driver.manage.timeouts().implicitlywait(long time (timeout time), TimeUnit unit (time unit))
Show waiting: WebDriver.Wait wait=new WebDriverWait();
                   WebElement element=wait.until(expectCondition);

show wait method

visibilityOfElementLocated(By locator) waits for the element to exist and be visible on the page

elementToBeClickable(By locator) Whether the page element is available and clickable on the page

elementToBeSelected (WedElement element) page element is selected

textToBePresentInElement(By locator) Whether to contain specific text in the page element

presenceOfElementLocated(By locator) page element exists in the page*/

    public void openBaidu() throws InterruptedException{
// webDriver.manage().window().maximize();//Maximize the browser
        //Set the invisible wait after the driver instantiation is completed, and set the timeout time to 5s
        // chromeDriver.manage().timeouts().implicitlyWait(time (timeout time), unit (time unit));
// chromeDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        chromeDriver.get("https://www.baidu.com");//Open Baidu, the address of the login box for testing
// Locate Baidu's search box element, and input data (ID positioning) - unique
        chromeDriver.findElement (By.id("kw")).sendKeys("Tencent Classroom");
        chromeDriver.findElement(By.id("su")).click();
        //The code is executed too fast, resulting in the UI not being displayed immediately, causing the two to be out of sync, so the element cannot be found
// Thread. sleep(3000);
        //Explicit waiting, take ExpectedConditions.visibilityOfElementLocated as an example
        WebDriverWait webDriverWait=new WebDriverWait(chromeDriver,5);
        webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()=' - Baidu Encyclopedia']")));

        chromeDriver.findElement(By.xpath("//a[text()=' - Baidu Encyclopedia']")).click();

    }
public void openBaidu() throws InterruptedException {
        // open the browser
        Path p1 = Paths. get("src", "drivers", "chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", p1.toAbsolutePath().toString());
        //Create a browser instance
        chromeDriver = new ChromeDriver();
        //Open the local file (because it is the same file used, so there is no change here)
        chromeDriver.get("D:\VsCodeword\\
ewWork\vue\demo\test.html");
        //click the button
        chromeDriver.findElement(By.id("abtn")).click();
        Thread. sleep(2000);
        //switchTo.alert find the corresponding alert prompt box
        //Alert alert=chromeDriver.switchTo().alert();
        //Click OK in the prompt box
        //alert. accept();
        //Cancel or x drop the prompt box
        //alert. dismiss();
        //The console prints the content of the popup box
        //System.out.println(alert.getText());
        Alert alert=chromeDriver.switchTo().alert();
        Thread. sleep(2000);
        //alert.accept();//Click OK, pop up 1
        //alert.dismiss();//Click to cancel, pop up 2
        //Thread. sleep(2000);
        //alert.accept();//Click to echo 1/2 of the bullet box to confirm
        System.out.println(alert.getText());
    }

/*#### Special element positioning and operation

##### ifame toggle

driver.switchTo().frame(index);

driver.switchTo().frame(id);

driver.switchTo().frame(name);

driver.switchTo().frame(WebElement);

Return to the default content page after switching (otherwise the element will not be found)

driver.switchTo().defaultContent();*/
public void iframe() throws InterruptedException {
        // open the browser
        Path p1 = Paths. get("src", "drivers", "chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", p1.toAbsolutePath().toString());
        //Create a browser instance
        chromeDriver = new ChromeDriver();
        //Open the local file (because it is the same file used, so there is no change here)
        chromeDriver.get("D:\VsCodeword\\
ewWork\vue\demo\test.html");
        chromeDriver.findElement(By.id("aa")).sendKeys("111");
        Thread. sleep(2000);
        chromeDriver.switchTo().frame("bframe");
        chromeDriver.findElement((By.id("bb"))).sendKeys("222");
        Thread. sleep(2000);
        chromeDriver.switchTo().frame("cframe");
        chromeDriver.findElement(By.id("cc")).sendKeys("333");
                //Back to the default page
        chromeDriver.switchTo().defaultContent();
        chromeDriver.findElement(By.id("aa")).clear();
        chromeDriver.findElement(By.id("aa")).sendKeys("Back to the outermost layer");
    }
/*##### select drop-down box

If the page element is a drop-down box, we can encapsulate this web element as a Select object.

Select selece=new Select(WebElement element);

Select object commonly used api

select.getOptions();//Get all options

select.selectByIndex(index);//Select the corresponding element according to the index

select.selectByValue(value);//Select the option corresponding to the specified value

select.selectByVisibleText(text);//Select the option corresponding to the text value*/
    @Test
    public void select() throws InterruptedException {
        // open the browser
        Path p1 = Paths. get("src", "drivers", "chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", p1.toAbsolutePath().toString());
        //Create a browser instance
        chromeDriver = new ChromeDriver();
        //Open the local file (because it is the same file used, so there is no change here)
        chromeDriver.get("https://www.baidu.com");
        //Open Baidu settings
        chromeDriver.findElement(By.id("s-usersetting-top")).click();
        //Click on advanced settings
        chromeDriver.findElement(By.xpath("//div[@id='s-user-setting-menu']/div/a[2]/span")).click();
        //Find the time selection drop-down box
        chromeDriver.findElement(By.xpath("//span[@id='adv-setting-gpc']/div/div/i")).click();
        // Select the corresponding option according to the index
        chromeDriver.findElement(By.xpath("//span[@id='adv-setting-gpc']/div/div[2]/div[2]/p[3]")).click();
        // Open the time drop-down box again
        chromeDriver.findElement(By.xpath("//span[@id='adv-setting-gpc']/div/div")).click();
        //select options
        chromeDriver.findElement(By.xpath("//span[@id='adv-setting-gpc']/div/div[2]/div[2]/p[4]")).click();
    }

time date control

If it can be entered manually, use the sendKeys method to enter the time

If there is a limit input, you can execute a piece of js to change the value of the element

JavascriptExecutor jsExecutor=(JavascriptExecutor)driver;

jsExecutor. executeScript(“…”);

//time and date control processing
//Ordinary input type time date control that can be input
//chromeDriver, get("https://ww,fligay,com/?ttid=sem,000000736shlreferid-baidu.082076aroute source=seo");
//chromeDriver,findElement(By.xpath("//form[@id='j_FlightForm']//input[@name=('depDate']")).sendKeys("2020-01-10");
//Limit input time and date control chromeDriver.qet("https://www.12306.cn/index/");
//javascript execution object
JavascriptExecutor javascriptExecutor =(JavascriptExecutor)chromeDriver;
//Call javascript to remove the readonly attribute in the input box whose id is train_date
javascriptExecutor.executecript("document.getElementById("train_date").removeAttribute("readonly") ");
Thread. sleep(1000);
chromeDriver,findElement(By,id("train_date")) .clear();
Thread. sleep(1000);
chromeDriver.findElement(By.id("train_date")).sendKeys("2020-01-10");



   //mouse operation
   @Test
    public void shubiao() {
        Path p1 = Paths. get("src", "drivers", "chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", p1.toAbsolutePath().toString());
        chromeDriver = new ChromeDriver();
        //mouse operation
        chromeDriver.get("http://www.treejs.cn/v3/demo/cn/exedit/drag.html");
        WebElement sourceElement = chromeDriver.findElement(By.id("treeDemo_2_span"));//Locate the moving element
        WebElement targetElement = chromeDriver.findElement(By.id("treeDemo_3_span"));//target element
        //Instantiate the actions object, mouse related operations
        Actions actions = new Actions(chromeDriver);
        actions.clickAndHold(sourceElement).moveToElement(targetElement).release().build().perform();
    }
}

File Upload

Divided into two cases: Similar to the following, use sendKeys to write the path of the file If the file upload is not an input element, but a third-party one controls. And it is not an input element, then this situation is very tricky, and some third-party tools, such as autoit, must be used to complete it.

chromeDriver, findElement(By.xpath("//input[@value='select file (value value)']")), sendKeys("Local file address, remember the escape of ");
Thread. sleep(2000);
chromeDriver.findElement(By.xpath("//input[@value='upload']")).click();

That’s about it. I’m going to introduce it with bricks. I may have written some things in a mess. Please forgive me.

GitHub – 854524301/javaAuto at master