selenium basic syntax


selenium basic syntax

1. Locating page elements

Elements of the page can be located through CSS selectors, such as common basic selectors, Id selectors, class selectors, compound selectors...

Through Chrome's F12 developer tool, right-click the corresponding label and select Copy to copy the selector. Copy the corresponding CSS. Select Copy xpath to copy the corresponding xpath.

  • Locate the element of the page through the driver.findElement method, the parameter of this method is the method in the abstract class By
  • Such as By.cssSelector() , By.xpath() , **By.id()**, etc.
  • It should be noted that no matter which method locates the element, it must be unique

insert image description here

public static void test1() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        Thread.sleep(1500);
        driver.get("https://www.baidu.com/");//打开连接
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("#kw")); //CSS选择
        driver.findElement(By.xpath("//*[@id=\"kw\"]"));// 通过xpath选择
        Thread.sleep(3000);
        driver.quit();//退出
    }

2. Operation of elements

1) Simulate keyboard input (send_keys)

  • After selecting the object through the corresponding selector, it can be input through send_keys
  • The following code is to enter CSDN in the Baidu input box
public static void test1() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        Thread.sleep(1500);
        driver.get("https://www.baidu.com/");//打开连接
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("#kw")).sendKeys("CSDN"); //CSS选择
        Thread.sleep(3000);
        driver.quit();//退出
    }

2) Click operation (click)

Click and submit can be realized by click , and submit can be realized by submit.

The operations that can be clicked may not necessarily be able to submit . Any element on the page can be clicked , so it is recommended to use it.

public static void test1() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        Thread.sleep(1500);
        driver.get("https://www.baidu.com/");//打开连接
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("#kw")).sendKeys("CSDN"); //CSS选择后在百度输入框输入CSDN
        Thread.sleep(1000);
        driver.findElement(By.xpath("//*[@id=\"su\"]")).click();//点击百度搜索按钮
        Thread.sleep(3000);
        driver.quit();//退出
    }

3) Clear the text content entered by the object (clear)

The contents of the input box can be cleared by clerar

public static void test1() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        Thread.sleep(1500);
        driver.get("https://www.baidu.com/");//打开连接
        Thread.sleep(1500);
        driver.findElement(By.cssSelector("#kw")).sendKeys("CSDN"); //CSS选择后在百度输入框输入CSDN
        Thread.sleep(1000);
        driver.findElement(By.cssSelector("#kw")).clear();//清空输入框的内容
        Thread.sleep(1000);
        driver.findElement(By.cssSelector("#kw")).sendKeys("leetcode");
        Thread.sleep(1000);
        driver.findElement(By.xpath("//*[@id=\"su\"]")).click();//点击百度搜索按钮
        Thread.sleep(3000);
        driver.quit();//退出
    }

4) Get text (gettext)

Text content can be obtained through gettext

For example, get the word news on Baidu's homepage

insert image description here

public static void test2() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.baidu.com/");
        Thread.sleep(1000);
        String str = driver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).getText();
        System.out.println(str);
    }

Note: It does not mean that all visible text on the page can become text, and some text is the attribute value corresponding to the attribute, and the text cannot be obtained through getText . You need to use the getAttribute method to get the attribute value.

For example, to get the attribute value of the Baidu click button
insert image description here

public static void test2() throws InterruptedException {
    
    
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    ChromeDriver driver = new ChromeDriver(options);
    driver.get("https://www.baidu.com/");
    Thread.sleep(1000);
    String str = driver.findElement(By.cssSelector("#su")).getAttribute("value");
    System.out.println(str);
}

3. wait

The execution speed of the code is very fast, but the rendering speed of the front-end response page is relatively slow. The possible result is: the code has been executed to the next step, the page has not been rendered, and the element cannot be found. So need to wait.

Waiting is divided into three types: mandatory waiting , implicit waiting , explicit waiting

  • mandatory wait

    Use Thread.sleep, let the program pause for a while, wait for the specified time and then continue to the next step.

    • Advantages: simple syntax, suitable for debugging
    • Disadvantages: The waiting time is fixed, resulting in a large consumption of testing time and greatly reducing the efficiency of automated testing.
  • implicit wait

    Within the specified time range, the polling waits for the element to appear and then ends immediately. If the element still does not appear within the specified time, a NoSuchElementException will be thrown

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    ChromeDriver driver = new ChromeDriver(options);
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(1));// 隐式等待1秒
    

    Implicit waiting acts on the entire life cycle of webdriver, as long as driver.quit is not executed, that is, the browser is not exited, implicit waiting always exists

    • Advantages: save a lot of waiting time, the next step can be executed immediately after the element is displayed, and the execution efficiency is high
    • Disadvantages: It is necessary to wait for all elements to be displayed before executing the next step, and there will still be extra time wasted (for example, the element we need to select has been rendered instantly, but other elements have not yet been rendered, so we need to wait for other elements to be displayed complete)
  • show wait

    Mandatory waiting can be tested against an element

    • WebDriverWait, the first parameter webdriver object, the second parameter, Duration class method, used to set the waiting time
    public static void test4() {
          
          
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            ChromeDriver driver = new ChromeDriver(options);
            driver.get("https://www.baidu.com/");
            WebDriverWait webDriverWait = new WebDriverWait(driver,Duration.ofSeconds(1));
            webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#kw")));
        
    

    When does the forced wait stop? Wait until the conditions in the brackets are met. If the conditions are not met within the specified time, an exception will be thrown.

    • Advantages: Waiting for a certain element greatly reduces the waiting time of automated testing
    • Disadvantages: complex writing
  • ExpectedConditions is a class in selenium that provides many methods for testing

    • ExpectedConditions.presenceOfElementLocated (check whether the corresponding element exists on the page)
    • ExpectedConditions.textToBe (check whether the text information corresponding to the page is correct)

It is not recommended to use implicit wait and mandatory wait in the code at the same time , and an unexpected result may occur if used at the same time.

4. Information printing

  • print the title ( getTitle() )
  • Print the current URL ( getCurrentUrl() )
public static void test5() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        Thread.sleep(1000);
        driver.get("https://www.baidu.com");
        Thread.sleep(1000);
        String title = driver.getTitle();
        String url = driver.getCurrentUrl();
        System.out.println("当前标题:"+title);
        System.out.println("当前url:"+url);
    }

But if we enter the Baidu homepage and click on the news page, the url and title are printed again, and the information on the homepage is still

insert image description here

public static void test5() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        Thread.sleep(2000);
        driver.get("https://www.baidu.com/");
        Thread.sleep(2000);
        String title = driver.getTitle();
        String url = driver.getCurrentUrl();
        System.out.println("当前标题:"+title);
        System.out.println("当前url:"+url);
        Thread.sleep(2000);
        // 点击切换到新闻页面
        driver.findElement(By.xpath("//*[@id=\"s-top-left\"]/a[1]")).click();
        Thread.sleep(2000);
        title = driver.getTitle();
        url = driver.getCurrentUrl();
        System.out.println("当前标题:"+title);
        System.out.println("当前url:"+url);
        Thread.sleep(2000);
        driver.quit();
    }

After clicking the hyperlink, a new tab page is opened. For selenium, it does not know what the page should be displayed. Selenium gives each tab page a unique identifier, called a handle.

insert image description here

5. window

  • Get the handle of the current page: driver.getWindowHandle()
  • Get handles of all tabs: driver.getWindowHandles()
  • Switch to the new tab page: driver.switchTo().window(handle)

Through the handle we can jump to the specified page

public static void test6() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.baidu.com");
        Thread.sleep(2000);
        // 获取百度首页句柄
        String window = driver.getWindowHandle();
        Thread.sleep(2000);
        // 点击按钮跳转得到新闻页面
        driver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();
        Thread.sleep(2000);
        // 获取所有标签页的句柄
        Set<String> windows = driver.getWindowHandles();
        for (String s : windows) {
    
    
            if (!s.equals(window)) {
    
    
                // 切换到新闻页窗口
                driver.switchTo().window(s);
            }
        }
        System.out.println("Title:"+driver.getTitle());
        System.out.println("Url:"+driver.getCurrentUrl());
        driver.quit();
    }

window size setting

  • Maximize: driver.manage().window().maximize()
  • Minimize: driver.manage().window().minimize()
  • Set the specified size: driver.manage().window().setSize(new Dimension(width, height)
public static void test7() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.baidu.com");
        Thread.sleep(1000);

        // 窗口最小化
        driver.manage().window().minimize();
        Thread.sleep(3000);
        // 窗口最大化
        driver.manage().window().maximize();
        Thread.sleep(3000);
        // 指定窗口大小
        driver.manage().window().setSize(new Dimension(1500,1000));
        Thread.sleep(3000);
        driver.quit();
    }

6. Navigation

The navigate interface is provided in selenium to realize page navigation

insert image description here

  • Forward: driver.navigate().forward()
  • Back: driver.navigate().back()
public static void test8() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        // 打开百度翻译
        driver.get("https://fanyi-pro.baidu.com/?hmsr=%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91&hmpl=%E5%9B%BA%E5%AE%9A%E5%85%A5%E5%8F%A3&hmcu=%E9%A1%B6%E9%83%A8%E6%8C%89%E9%92%AE");
        // 点击日常快译
        driver.findElement(By.xpath("//*[@id=\"whole-page-header\"]/div/ul/li[2]/a")).click();
        Thread.sleep(2000);
        // 后退
        driver.navigate().back();
        Thread.sleep(1500);
        // 前进
        driver.navigate().forward();
        Thread.sleep(1500);
        // 后退
        driver.navigate().back();
        Thread.sleep(1500);
        // 前进
        driver.navigate().forward();
        Thread.sleep(2000);
        driver.quit();
    }

7. Pop-up window

Selenium cannot directly compile the js language, but it can still use the method to execute the Js language, using driver.executeScript(js language)

This method is similar to executing Js in F12

public static void test9() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.baidu.com");
        driver.executeScript("alert('test')");
        Thread.sleep(2000);
        driver.quit();
    }

Ordinary pop-up windows that can be located in the front-end code can use the **driver.findElement()** method to locate elements, but there are still some pop-up windows that cannot be located.

Warning pop-up windows and confirmation pop-up windows cannot locate elements in the front-end code, and need to use the Alert interface provided in Selenium to handle
insert image description here

Alert alert = driver.switchTo().alert();
alert.accept();// 点击弹窗上的确认按钮
alert.dismiss();//点击弹窗上的取消按钮

Prompt pop-up

insert image description here

the code

Alert alert = driver.switchTo().alert();
alert.sendKeys("哈哈哈");// 输入
Thread.sleep(2000);
alert.accept();

8. Mouse and Popups

Selenium provides the Actions interface

Move the mouse over the specified element

Key code: actions.clickAndHold(element).perform()

public static void test12() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.baidu.com");
        Thread.sleep(2000);
        WebElement element = driver.findElement(By.cssSelector("#form > span.bg.s_ipt_wr.new-pmd.quickdelete-wrap > span.soutu-btn"));
        Actions actions = new Actions(driver);
        actions.clickAndHold(element).perform();
        Thread.sleep(3000);
        driver.quit();
    }

keyboard input sendKeys

driver.findElement(By.cssSelector("#kw")).sendKeys("CSDN");

9. Select box

Selenium provides the select interface

insert image description here

  • selectByValue: select through the values ​​attribute
  • selectByIndex: select by index, the index starts from 0
  • selectByVisibleText: select by the courseware text in option
<select>
	<option value="default">请选择</option>
	<option value ="one">吃饭</option>
	<option value ="tow">睡觉</option>
	<option value="three">打豆豆</option>

</select>
public static void test13() throws InterruptedException {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);

        driver.get("./test.html");
        Thread.sleep(2000);
        WebElement element = driver.findElement(By.xpath("/html/body/select"));
        Select select = new Select(element);
        select.selectByValue("one");
        Thread.sleep(2000);
        select.selectByIndex(0);
        Thread.sleep(2000);
        select.selectByVisibleText("打豆豆");
        Thread.sleep(1000);
        driver.quit();
    }

10. File upload

Clicking on the upload file on the page will pop up a system window, and selenium cannot operate the system window.

Enter the file path and file name we want to upload through the sendKey method, and then we can achieve an operation of file upload

insert image description here

// 获取上传文件按钮
WebElement element = driver.findElement(By.cssSelector("#uploadImg"));
// 指定路径选择文件
element.sendKeys("C:\\Users\\HeHanYu\\Desktop\\code\\spring.jpg");

11. Screenshots

Selinium also provides a screenshot API, which can verify that the execution speed of the code is much faster than the rendering speed of the page.

public static void test15() {
    
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.baidu.com");
        driver.findElement(By.cssSelector("#kw")).sendKeys("selenium");
        driver.findElement(By.cssSelector("#su")).click();
        // 屏幕截图
        File srcFile = driver.getScreenshotAs(OutputType.FILE);
        // 将截图问价保存到指定路径下
        File fileName = new File("./src/test/img/demo.jpg");
        FileUtil.copyFile(srcFile,fileName);

    }

After clicking search, I took a screenshot and found that the page was not rendered, so some waiting operations should be used when using selenium to operate page elements

insert image description here


Guess you like

Origin blog.csdn.net/weixin_53946852/article/details/131061050