selenium自动化学习笔记(Java版)

       背景:selenium是python爬虫,同时也是自动化测试使用的一个模块,当然不止有python语言版,本文就是Java版,因为python相关的博客很多了,而我个人更加倾向使用Java到实际的工作项目中。在几年前,尤其是没有做过web相关开发之前,曾经使用过不少python进行过爬虫练习,但都是零零星星地跟着其它博客的例子进行学习,改造成为自己的需求。不过,在经历了webgis开发,部分Java开发甚至安卓移动端自动化(用的是Auto.js,后面的文章有时间会写相关的内容)后,便有了想往PC端浏览器学习扩展的想法,于是就有了这篇文章。

        这个例子是以12306网站进行练习记录一些常见的PC浏览器的HTML domcument文档元素的查找方法和操作动作(模拟交互)如:查找element(根据id,根据class,根据标签名,根据css选择器,根据xpath等等)的相关信息或对象,模拟鼠标,键盘动作,浏览器对象操作方法。在这不对每一个方法单独拆分写,顺序稍微乱些。

使用maven管理包,pom.xml如下:



    4.0.0

    org.example
    seleniumApiTest
    1.0-SNAPSHOT
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.6
                    1.6
                
            
        
    

    

        
        
            org.seleniumhq.selenium
            selenium-java
            3.4.0
        

    

Java代码:

package com.seleniumApi.test;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
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;

import java.io.File;
import java.util.List;
import java.util.Set;

public class apitest {
    public static  void main(String [] args) throws InterruptedException {
        //驱动插件下载链接:https://npm.taobao.org/mirrors/chromedriver,根据自己的chrome浏/览器版本确定下载
        System.setProperty("webdriver.chrome.driver","C:\\driver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        //https://blog.csdn.net/qq_22003641/article/details/79137327?utm_source=app

        //控制浏览器大小方法
        //最大化浏览器
        driver.manage().window().maximize();
        //指定浏览器大小
        //driver.manage().window().setSize(new Dimension(1200,600));
        driver.get("https://www.12306.cn/index/");
        //driver.get("https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=%E5%B9%BF%E5%B7%9E%E5%8D%97,IZQ&ts=%E6%B7%B1%E5%9C%B3%E5%8C%97,IOQ&date=2020-10-31&flag=N,N,Y");
        //查找元素的八种方法,以12306网址为例

        //id
        WebElement id=driver.findElement(By.id("fromStationText"));
        System.out.println("id:"+id.getTagName());
        //name
        WebElement name=driver.findElement(By.name("from_station"));
        System.out.println("name:"+name.getTagName());
        //class name
        WebElement fromlabel=driver.findElement(By.className("form-label"));
        System.out.println("fromlabel:"+fromlabel.getTagName());
        System.out.println("fromlabel:"+fromlabel.getText());
        //tag name
        WebElement tagname=driver.findElement(By.tagName("label"));
        System.out.println("tagname:"+tagname.getTagName());
        System.out.println("tagname:"+tagname.getText());


        //partial link text

        WebElement partialLinkText=driver.findElement(By.partialLinkText("登录"));
        System.out.println("partialLinkText:"+partialLinkText.getTagName());
        System.out.println("partialLinkText:"+partialLinkText.getText());

        //xpath
        /**参考
         * driver.findElement(By.xpath("//*[@id='kw']"))
         * driver.findElement(By.xpath("//*[@name='wd']"))
         * driver.findElement(By.xpath("//input[@class='s_ipt']"))
         * driver.findElement(By.xpath("/html/body/form/span/input"))
         * driver.findElement(By.xpath("//span[@class='soutu-btn']/input"))
         * driver.findElement(By.xpath("//form[@id='form']/span/input"))
         * driver.findElement(By.xpath("//input[@id='kw' and @name='wd']"))
         */
        WebElement xpath=driver.findElement(By.xpath("/html/body/div/a/i"));

        System.out.println("xpath:"+xpath.getTagName());
        System.out.println("xpath:"+xpath.getText());

        //css selector
        /**
         参考
         driver.findElement(By.cssSelector("#kw")
         driver.findElement(By.cssSelector("[name=wd]")
         driver.findElement(By.cssSelector(".s_ipt")
         driver.findElement(By.cssSelector("html > body > form > span > input")
         driver.findElement(By.cssSelector("span.soutu-btn> input#kw")
         driver.findElement(By.cssSelector("form#form > span > input")
         */
        WebElement cssselector=driver.findElement(By.cssSelector("html>body>div>a>i"));
        System.out.println("cssselector:"+cssselector.getTagName());
        System.out.println("cssselector:"+cssselector.getText());

        Thread.sleep(1000);

        WebElement date_input=driver.findElement(By.id("train_date"));



        date_input.click();


        //WebElement css1=driver.findElement(By.cssSelector(".cal-wrap.cal.cal-cm.cell.so"));

        //System.out.println("css1:"+css1.getText());
        /**
         * 多个选择含有多个子元素Nodelist
         * document.querySelectorAll(".cal-wrap.cal.cal-cm.cell")
         * NodeList []
         * document.querySelectorAll(".cal-wrap")
         * NodeList [div.cal-wrap]0: div.cal-wrapaccessKey: ""align: ""ariaAtomic: nullariaAutoComplete: nullariaBusy: nullariaChecked: nullariaColCount: nullariaColIndex: nullariaColSpan: nullariaCurrent: nullariaDescription: nullariaDisabled: nullariaExpanded: nullariaHasPopup: nullariaHidden: nullariaKeyShortcuts: nullariaLabel: nullariaLevel: nullariaLive: nullariaModal: nullariaMultiLine: nullariaMultiSelectable: nullariaOrientation: nullariaPlaceholder: nullariaPosInSet: nullariaPressed: nullariaReadOnly: nullariaRelevant: nullariaRequired: nullariaRoleDescription: nullariaRowCount: nullariaRowIndex: nullariaRowSpan: nullariaSelected: nullariaSetSize: nullariaSort: nullariaValueMax: nullariaValueMin: nullariaValueNow: nullariaValueText: nullassignedSlot: nullattributeStyleMap: StylePropertyMap {size: 4}attributes: NamedNodeMap {0: class, 1: style, class: class, style: style, length: 2}autocapitalize: ""autofocus: falsebaseURI: "https://www.12306.cn/index/"childElementCount: 3childNodes: NodeList(3) [div.cal, div.cal.cal-right, div.cal-ft]children: HTMLCollection(3) [div.cal, div.cal.cal-right, div.cal-ft]classList: DOMTokenList ["cal-wrap", value: "cal-wrap"]className: "cal-wrap"clientHeight: 211clientLeft: 1clientTop: 1clientWidth: 604contentEditable: "inherit"dataset: DOMStringMap {}dir: ""draggable: falseelementTiming: ""enterKeyHint: ""firstChild: div.calfirstElementChild: div.calhidden: falseid: ""innerHTML: "
css1=driver.findElements(By.cssSelector(".cal-wrap.cal.cal-cm.cell")); List css1=driver.findElements(By.cssSelector(".cell")); System.out.println("cssselector1:"+css1.size()); for(WebElement css : css1 ){ System.out.println("css:"+css.getLocation()); System.out.println("css:"+css.getTagName()); System.out.println("css:"+css.getText()); } Thread.sleep(5000); //link text WebElement linktext=driver.findElement(By.linkText("登录")); System.out.println("linktext:"+linktext.getTagName()); System.out.println("linktext:"+linktext.getText()); linktext.click(); Thread.sleep(1000); //控制浏览器前进后退、刷新等操作 //回退 driver.navigate().back(); Thread.sleep(1500); //前进 driver.navigate().forward(); Thread.sleep(1500); //回退 driver.navigate().back(); Thread.sleep(1500); //刷新页面 driver.navigate().refresh(); Thread.sleep(1500); //WebElement常用的方法 WebElement searchinput=driver.findElement(By.className("search-input")); //获取当前窗口句柄 String current_windows=driver.getWindowHandle(); //模拟鼠标方法 //除了click外,还有右击contextClick()、鼠标点击并控制clickAndHold()、 //双击doubleClick()、拖动dragAndDrop()、释放鼠标release()、perform()执行所有Actions中存储的行为 Actions actions=new Actions(driver); actions.contextClick(searchinput).perform(); System.out.println("contextClick"); Thread.sleep(5000); actions.doubleClick(searchinput).perform(); System.out.println("doubleClick"); Thread.sleep(5000); WebElement xinxi= driver.findElement(By.className("menu-nav-hd")); actions.clickAndHold(xinxi).perform(); System.out.println("clickAndHold"); Thread.sleep(5000); File file=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try{ FileUtils.copyFile(file,new File("d://Screenshot.png")); }catch (Exception e){ e.printStackTrace(); } actions.dragAndDrop(xinxi,searchinput).perform(); System.out.println("dragAndDrop"); Thread.sleep(1000); actions.release(); System.out.println("release"); Thread.sleep(5000); //模拟键盘方法 //点击进入搜索框 searchinput.click(); Thread.sleep(1000); //输入文字 searchinput.sendKeys("退票跑"); Thread.sleep(1000); //回退键 searchinput.sendKeys(Keys.BACK_SPACE); Thread.sleep(1000); //快捷键 Ctrl+a、x、v searchinput.sendKeys(Keys.CONTROL,"a"); Thread.sleep(1000); searchinput.sendKeys(Keys.CONTROL,"x"); Thread.sleep(1000); searchinput.sendKeys(Keys.CONTROL,"v"); Thread.sleep(1000); //使用Enter键代替submit方法 searchinput.sendKeys(Keys.ENTER); Thread.sleep(5000); //submit提交 //searchinput.submit(); //窗口切换 //获取所有窗口句柄 Set all_windows=driver.getWindowHandles(); //显示等待,针对某个元素等待 //driver: 浏览器驱动。 10: 最长超时时间, 默认以秒为单位。 1: 检测的的间隔(步长) 时间, 默认为 0.5s。 WebDriverWait wait=new WebDriverWait(driver,10,1); // for (String eachwindows : all_windows){ if (!eachwindows.equals(current_windows)){ System.out.println("切换到之前的页面(12306首页)"); //切换到之前的页面(12306首页) driver.switchTo().window(eachwindows); Thread.sleep(8000); //关闭当前窗口 driver.close(); driver.switchTo().window(current_windows); //Thread.sleep(2000); wait.until(new ExpectedCondition() { @Override public WebElement apply(WebDriver driver1){ System.out.println("wait.until"); return driver1.findElement(By.id("fromStationText")); } }); break; } } //出发城市 WebElement fromStation =driver.findElement(By.id("fromStationText")); //清除输入框的内容 fromStation.clear(); Thread.sleep(1000); //点击输入框 fromStation.click(); Thread.sleep(1000); //输入框输入关键字 fromStation.sendKeys("广州南"); Thread.sleep(1000); WebElement citylineover1=driver.findElement(By.className("citylineover")); citylineover1.click(); // 到达城市 WebElement toStation=driver.findElement(By.id("toStationText")); toStation.clear(); Thread.sleep(1000); toStation.click(); Thread.sleep(1000); toStation.sendKeys("深圳北"); Thread.sleep(1000); WebElement citylineover2=driver.findElement(By.className("citylineover")); citylineover2.click(); Thread.sleep(1000); //toStation.submit(); //日期 WebElement train_date=driver.findElement(By.id("train_date")); //点击所选的日期,假如是这个月的31日 train_date.click(); Thread.sleep(1000); //日期控件 WebElement cal_cm=driver.findElement(By.className("cal-cm")); List cells = cal_cm.findElements(By.className("cell")); //选择31号 for (WebElement cell : cells){ WebElement so=cell.findElement(By.className("so")); String name1=so.getText(); if ("31".equals(name1)){ System.out.println("日期:"+name1); cell.click(); Thread.sleep(1000); break; } } Thread.sleep(1000); String current_Handle= driver.getWindowHandle(); //查询按钮 WebElement search_one=driver.findElement(By.id("search_one")); search_one.click(); Thread.sleep(1000); //下拉框选择方法 Set all_Handle= driver.getWindowHandles(); //切换到第二个窗口 for(String handle : all_Handle){ if (!handle.equals(current_Handle)){ driver.switchTo().window(handle); Thread.sleep(1000); System.out.println("currentURL:"+driver.getCurrentUrl()); break; } } //WebElement selectsmall=driver.findElement(By.className("select-small")); WebElement selectsmall=driver.findElement(By.id("cc_start_time")); //WebElement selectsmall=driver.findElement(By.cssSelector(".pos-top.select-small")); Select select=new Select(selectsmall); //选择12-18点之间的 select.selectByValue("12001800"); Thread.sleep(2000); System.out.println("选择12-18点之间的"); select.selectByIndex(0); Thread.sleep(2000); System.out.println("选择0-24点之间的"); select.selectByIndex(1); Thread.sleep(2000); System.out.println("选择0-6点之间的"); select.selectByIndex(2); Thread.sleep(2000); System.out.println("选择6-12点之间的"); select.selectByIndex(3); Thread.sleep(2000); System.out.println("选择12-18点之间的"); select.selectByIndex(4); Thread.sleep(2000); System.out.println("选择18-24点之间的"); //cookie方法 //获取cookie Set cookies=driver.manage().getCookies(); System.out.println("cookies:"+cookies.toString()); //删除cookie for(Cookie cookie :cookies){ if ("_jc_save_fromDate".equals(cookie.getName())){ driver.manage().deleteCookie(cookie); System.out.println("cookie:"+cookie.getName()); break; } } Set cookies1=driver.manage().getCookies(); System.out.println("cookies:"+cookies1.toString()); //设置(添加)cookie Cookie cookie1=new Cookie("_jc_save_fromDate","2020-10-20"); //Cookie cookie2=new Cookie("value","2020-10-20"); driver.manage().addCookie(cookie1); //driver.manage().addCookie(cookie2); Set cookies2=driver.manage().getCookies(); System.out.println("cookies:"+cookies2.toString()); //截屏窗口 /**File file=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try{ FileUtils.copyFile(file,new File("d://Screenshot.png")); }catch (Exception e){ e.printStackTrace(); } */ //执行JavaScript脚本 String javascript="alert('执行了JavaScript代码!')"; ((JavascriptExecutor)driver).executeAsyncScript(javascript); System.out.println("执行了JavaScript代码"); Thread.sleep(2000); //警告框处理 警告框这里还有点问题,后续继续研究 /** * getText(): 返回 alert/confirm/prompt 中的文字信息。 * accept(): 接受现有警告框。 * dismiss(): 解散现有警告框。 * sendKeys(keysToSend): 发送文本至警告框。 * keysToSend: 将文本发送至警告框 */ //driver.switchTo().alert().accept(); Alert alert= driver.switchTo().alert(); alert.accept(); System.out.println("accept"); Thread.sleep(1000); //alert.getText(); System.out.println("getText:"+alert.getText()); Thread.sleep(1000); alert.sendKeys("小星星"); System.out.println("getText"); Thread.sleep(1000); alert.dismiss(); System.out.println("dismiss"); Thread.sleep(1000); } }

你可能感兴趣的:(java,selenium,自动化)