Selenium的自我总结2_元素基本操作

对于Selenium的基本元素的操作,就自己的了解做了一个基本的介绍,这篇直接上代码,针对一个页面如何操作写了些基本的操作脚本,希望对初学者有一定的帮助,也希望通过这些总结让自己有一些清晰的认识和了解:

Demo文件下载地址:http://pan.baidu.com/s/1sjECS5B

Demo 的样图:

Java Code:

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class BasicUIExercise {

    WebDriver driver;

    public void openBrowser() {

        System.setProperty("webdriver.chrome.driver",
                "E:\\JavaCodeWorkSpace\\JProject0610\\ChromeDriver\\chromedriver.exe");

        driver = new ChromeDriver();

    }

    // 退出所有浏览器
    public void quitBrowser() {

        driver.quit();

    }

    // 退出当前的单个浏览器
    public void closeBrowser() {

        driver.close();

    }

    public void goToTarget(String URL) {

        driver.navigate().to(URL);
        driver.navigate().refresh();
        // driver.get(URL);

    }

    public void backToTarget() {

        driver.navigate().back();

    }

    public void waitTime() {

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    }

    public void maxWindow() {

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

    }

    // 拖动页面滚动条到最低部
    public void executeJS(String script) {

        // String js = "var q=document.documentElement.scrollTop=10000";
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript(script);
    }

    public void testInput(String value) {

        WebElement element = driver.findElement(By
                .xpath(".//*[@id=‘input‘]/input"));
        // element.clear();
        element.sendKeys(value);
        String inputValue = element.getAttribute("value");
        System.out.println(inputValue);

    }

    public void testClickLink() throws InterruptedException {

        WebElement element = driver.findElement(By.className("baidu"));
        System.out.println("The Link is: " + element.getAttribute("href"));
        element.click();
        System.out.println("Current Page Title is:" + driver.getTitle());
        Thread.sleep(3000);

    }

    public void testSelect(int index) {

        WebElement element = driver.findElement(By.name("select"));
        Select select = new Select(element);
        select.selectByIndex(index);
        String selectText = select.getFirstSelectedOption().getText();
        System.out.println("Curretn Select is: " + selectText);

    }

    public void testRadioBox(int index) {

        List<WebElement> elements = driver.findElements(By.name("identity"));
        WebElement element = elements.get(index);
        element.click();
        boolean flag = element.isSelected();
        getClass();
        System.out.println("the radioBox is Select:" + flag);

    }

    public void testMultipleBox() {

        List<WebElement> elements = driver.findElements(By
                .xpath(".//*[@id=‘checkbox‘]/input"));
        for (WebElement element : elements) {

            element.click();
            boolean flag = element.isSelected();
            System.out.println("the CheckBox is select:" + flag);

        }

    }

    public void testBtn() {

        WebElement element = driver.findElement(By.className("button"));
        element.click();
        String btnText = element.getAttribute("value");
        System.out.println(btnText);

    }

    public void testAlert() throws InterruptedException {

        WebElement element = driver.findElement(By
                .xpath(".//*[@id=‘alert‘]/input"));
        element.click();
        Thread.sleep(1000);
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println("ALert Text is:" + alertText);
        alert.accept();
    }

    // Selenium是无法识别Windows对话框的,所以在上传文件的过程中根据浏览器的不同,需要使用到AutoIT这个工具来获取Windows对话框实现上传的功能
    public void testUploadFile(String filePath) {

        WebElement element = driver.findElement(By.id("load"));
        element.sendKeys(filePath);

    }

    public void testOpneNewWindow() {

        WebElement element = driver.findElement(By.xpath(".//*[@id=‘open‘]/a"));
        element.click();

        String currentHandle = driver.getWindowHandle();
        Set<String> handles = driver.getWindowHandles();
        Iterator<String> iterators = handles.iterator();
        while (iterators.hasNext()) {

            String handle = iterators.next();
            if (!(currentHandle.equals(handle))) {

                driver.switchTo().window(handle);
                System.out.println("testOpneNewWindow Current Web Title: "
                        + driver.getTitle());
                this.closeBrowser();

            }

        }
        driver.switchTo().window(currentHandle);
    }

    // 将鼠标移动到该Btn下面,就会有对应的信息显示
    public void testAction() {

        WebElement element = driver.findElement(By.className("over"));
        Actions actions = new Actions(driver);
        actions.moveToElement(element).build().perform();
        String actionText = driver.findElement(By.id("over")).getText();
        System.out.println("The Action Text is: " + actionText);

    }

    //testAction弹出的信息得首先处理掉,不然testElementDisplayedWait无法定位到当前的页面,聚焦点依然在testAction上面的信息上面
    public void testActionJavaScript() {
        JavascriptExecutor js2 = (JavascriptExecutor) driver;
        js2.executeScript("alert(‘Hello Selenium Web Test!‘)");
        Alert alert = driver.switchTo().alert();
        String text = alert.getText();
        System.out.println(text);
        alert.accept();
    }

    public void testElementDisplayedWait() {

        WebElement element = driver.findElement(By.className("wait"));
        element.click();
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(new ExpectedCondition<Boolean>() {

            @Override
            public Boolean apply(WebDriver driver2) {

                return driver2.findElement(By.className("red")).isDisplayed();
            }

        });
        System.out.println("The context is:"
                + driver.findElement(By.className("red")).getText());

    }

    public static void main(String[] args) throws InterruptedException {

        BasicUIExercise bue = new BasicUIExercise();
        bue.openBrowser();
        bue.maxWindow();
        bue.waitTime();
        bue.goToTarget("E:\\JavaCodeWorkSpace\\JProject0610\\WebAddress\\demo2.html");
        bue.testInput("Test WebDriver Study");
        bue.testClickLink();
        bue.backToTarget();
        bue.testSelect(4);
        bue.testRadioBox(5);
        bue.testMultipleBox();
        bue.testBtn();
        bue.testAlert();
        bue.executeJS("var q=document.documentElement.scrollTop=10000");
        bue.testUploadFile("E:\\JavaCodeWorkSpace\\JProject0610\\WebAddress\\demo2.html");
        bue.testOpneNewWindow();
        bue.testAction();
        bue.testActionJavaScript();
        bue.testElementDisplayedWait();
        Thread.sleep(1000);
        bue.quitBrowser();

    }

}
时间: 2024-08-03 17:41:33

Selenium的自我总结2_元素基本操作的相关文章

Selenium Web 自动化 - 如何找到元素

Selenium Web 自动化 - 如何找到元素 2016-07-29 1. 什么是元素? 元素:http://www.w3school.com.cn/html/html_elements.asp 2. 定位方式解析 Selenium WebDriver 提供一个先进的技术来定位 web 页面元素.Selenium 功能丰富的API 提供了多个定位策略如:Name.ID.CSS 选择器.XPath 等等,如下图所示: 一般会用ID来定位,因为它是唯一的,xpath也比较通用,火狐浏览器插件:f

Selenium with Python 003 - 页面元素定位

WebUI自动化,首先需要定位页面中待操作的元素,然后进行各种事件操作,这里我们首先介绍Selenium Python 如何定位页面元素,WebDriver 提供了一系列的方法. 定位单个页面元素(返回单个元素对象) find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag

【Selenium专题】高亮显示页面元素

高亮显示页面元素主要用到Selenium中使用js的知识点,最常用的是检查元素定位是否正确.此外,实现js的调用大大增强了Selenium的功能.以下是调试通过的案例: import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class js { public static

Selenium Webdriver——操作隐藏的元素

有时候我们会碰到一些元素不可见,这个时候selenium就无法对这些元素进行操作了.例如,下面的情况: 页面主要通过“display:none”来控制整个下拉框不可见.这个时候如果直接操作这个下拉框,就会提示: from selenium import webdriver from selenium.webdriver.support.select import Select import os,time driver = webdriver.Chrome() file_path = 'file

python selenium系列(二)元素定位方式

一 前言 元素定位,是操作元素的第一步,也是WebUI自动化的难点和核心. 二 元素定位方法 selenium提供了内置的方法完成对待操作元素的定位,主要分为8类,其中,每类又可细分为定位单个元素和定位多个元素,另外还提供了2个私有方法.详细如下: 定位单个元素 ·         find_element_by_id ·         find_element_by_name ·         find_element_by_xpath ·         find_element_by_

python selenium系列(四)元素等待

一 前言 在前面的selenium系列(二)元素定位方式和selenium系列(三)常用操作类型及方法两节中,已经介绍了web页面元素的识别定位.操作等技术,可能你会觉得掌握这两项技术就可以实施web自动化了,答案基本是这样的,毕竟元素定位和操作是核心技术.但是,在某些场景,脚本的运行并非预期那样,如,要操作的元素用常规方法无法识别.元素可以识别但在脚本运行时却未如期而至等.为了解决这些疑难杂症,接下来三节内容将会介绍处理这些问题的通用方法. 在本节,主要介绍元素等待的使用方法和场景,该方法是开

Python selenium PO By.XPATH定位元素报错

Python selenium PO  By.XPATH定位元素报错 如下代码经常报错: # 首页的“新建投放计划”按钮 new_ads_plan = (By.XPATH, "//*[text()='百度新闻']/..") print(type(self.new_ads_plan)) self.driver.find_element(self.new_ads_plan).click() 运行经常报错:selenium.common.exceptions.WebDriverExcepti

Python + Selenium(二)网页元素定位(一)

元素定位是 WebDriver 很重要的部分,特别对于自动化测试来说. 要想操作元素,首先必须要找到元素. 我们做自动化测试,就是需要通过模拟手工对元素的操作来实现自动化.脚本无法做到指哪打哪,不能像手工操作那样鼠标移过去点一下就行,毕竟代码没有自我辨别能力. 开发者工具 开发者工具是浏览器自带的网页调试工具,其中最好用的要数谷歌浏览器(Chrome)和火狐浏览器(Firefox).一般通过 F12 快捷键就可以打开.通过此工具可以查看网页元素来寻找可以定位的方法. 首先,我们打开百度首页(ht

selenium测试(Java)--元素操作(五)

元素的操作有 1. 清除文本 2. 模拟按键输入 3. 单击元素 4. 返回元素尺寸 5. 获取文本 6. 获取属性值 7. 判断是否可见 8. 提交 下面通过操作新浪邮箱的注册界面的脚本来展示使用方法 源代码: package com.test.elementoperation; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;