java+selenum实现网页自动化总结

Java Selenium个人学习笔记

 Selenium简介:

支持多种语言。基于Java语言,Selenium 3.0版本,用的框架是TestNG框架

支持浏览器:IE,Chrome,FireFox,Safari。支持Windows,Mac系统平台上运行


1.       Selenium Client& WebDriver (Selenium驱动)

下载地址: http://docs.seleniumhq.org/download/


将其任意解压至本地路径,之前用的2.48.2版本,解压内容如下:



 

2.       IE Driver (IE浏览器驱动):

下载地址: http://docs.seleniumhq.org/download/,注意区分32位和64位系统

下载解压如下:

 

Notes: 建议选择32位驱动下载,在64位驱动中,会出现输入文字过慢的情况,在32位驱动中不存在该情况

 

3.       ChromeDriver(Chrome浏览器驱动):

下载地址:http://chromedriver.storage.googleapis.com/index.html

当前最新版本是2.33,点击该文件夹,如下图所示:

目前似乎只有32位的浏览器驱动,只有选择这个。

下载解压如下:

 

4.       Gecko Driver(Firefox浏览器驱动)

自Selenium进入3.0版本后,Firefox的驱动独立于Selenium组件,需要另行单独下载,不再自带

下载地址:https://github.com/mozilla/geckodriver/releases,注意区分32位和64位系统,这里依然推荐使用32位版本的驱动。

 

选择32位驱动下载,解压如下:

 

NOTES: 为了方便管理,建议将这些解压缩的驱动文件放置在一个文件夹内方便管理和后续的调用使用。


5.       TestNG

下载地址:http://www.dataguru.cn/thread-472787-1-1.html

 


使用方法:

1)       将解压后的文件..\eclipse-testng离线包\features\目录下的文件夹org.testng.eclipse_6.8.6.20130607_0745放到eclipse--》features目录下

2)       将解压后的文件..\eclipse-testng离线包\org.testng.eclipse_6.8.6.20130607_0745文件夹放到eclipse--》plugins目录下

3)       重启eclipse

 

Note:全套直接(Eclispe+TestNG)下载地址: http://pan.baidu.com/s/1i5hU1y1

另外,Firefox不需要另外安装驱动,只需要安装浏览器即可

 

 搭建和配置Selenium+TestNG的框架

1.       新创建一个Java Project,随后将Selenium驱动的内容都导入进该Project

步骤如下图所示:

 







 

需要说明的是需要引入的内容有:selenium-java-2.48.2.jar, selenium-server-standalone-2.48.2.jar和libs中所有的jar包。2.48.2是版本号,根据不同版本号,文件名不同。

最后引进的包会在Referenced Libraires出现

 

2.      新建第一个TestNG框架

1)      新建Package, 步骤:src右键 -> new -> package -> 自定义名字 ->Finish

如下图所示


创建完毕后如下:

 

2)      新建TestNG框架

步骤:选中Pakcage名字右键 -> New -> Other -> 搜索TestNG–> Next -> 自定义名称 -> 勾选 @BeforeMethod 和@AfterMethod -> Finish

如下图所示:


 


 

创建完会生成代码,如下所示:


Note: 关于TestNG的annoations(注解)的优先级执行顺序可参考:

http://www.yiibai.com/selenium/selenium_test_ng.html

一般创建TestNG后只选择@beforeMethod 和 @afterMethod

 

3)      编写测试代码

利用脚本访问百度首页,下列是代码解释

 

具体代码:

package MySelenium;

 

import org.testng.annotations.Test;

import org.testng.annotations.BeforeMethod;

import org.openqa.selenium.Dimension; //引入的Dimension类

import org.openqa.selenium.WebDriver; //引入的Webdriver类

importorg.openqa.selenium.chrome.ChromeDriver; //引入的Chromedriver类

import org.testng.annotations.AfterMethod;

 

public class Demo1 {

       publicWebDriver driver; //新建全局WebDriver类的变量,命名为driver

       StringURL="http://www.baidu.com"; //初始化URL变量为百度首页

 @Test

 public void f() throws Exception {

         driver.navigate().to(URL); //打开URL中指定的网站

         Thread.sleep(5000); //等待5秒

  }

 @BeforeMethod

 public void beforeMethod() {

        System.setProperty("webdriver.chrome.driver","D:\\Selenium\\ChromeDriver\\ChromeDriver.exe"); 

         //设置ChromeDriver的属性,并将其本地的位置贴进来,能够被调用

        

         driver = new ChromeDriver(); //将driver初始化为Chromedriver

         driver.manage().window().setSize(newDimension(1920,1080)); //将浏览器大小设置为1920,1080大小

  }

 

 @AfterMethod

 public void afterMethod() {

       driver.quit();//退出浏览器

        

  }

 

}

 

4)      运行和结果展示

右击空白处,点击Run As -> TestNG Test

 

打开百度首页

 

结果内容在下方console端显示

 


5)      小优化:为了每次不在@beforeMethod写启动浏览器方法显得冗余,可以创建一个java类方法直接调用。

n  先将IE和Chrome的驱动导入到Project中,如下所示

 

n  创建一个新的java类,随后编写代码如下:


代码:

package MySelenium;

 

import java.io.File;

 

import org.openqa.selenium.Dimension;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.chrome.ChromeDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.ie.InternetExplorerDriver;

 

public class GetBrowser {

       publicstatic WebDriver driver;

      

       publicstatic WebDriver GetIE() { //获取IE浏览器驱动方法

              FileIEDriverFile = new File ("BrowserDrivers\\IEDriverServer.exe");         

              System.setProperty("webdriver.ie.driver",IEDriverFile.toString());

              driver= new InternetExplorerDriver();

              driver.manage().window().setSize(newDimension(1920,1080));

              returndriver;

       }

      

       publicstatic WebDriver GetChrome() { //获取Chrome浏览器驱动方法

              FileChromeDriverFile = new File ("BrowserDrivers\\chromedriver.exe");     

              System.setProperty("webdriver.chrome.driver",ChromeDriverFile.toString());

              driver= new ChromeDriver();

              driver.manage().window().setSize(newDimension(1920,1080));

              returndriver;

       }

      

       publicstatic WebDriver GetFireFox() { //获取FireFox浏览器驱动方法

              System.setProperty("webdriver.firefox.bin","C:/Program Files/Mozilla Firefox/firefox.exe"); //指定firefox的安装路径

              driver = new FirefoxDriver();

              driver.manage().window().setSize(newDimension(1920,1080));

              returndriver;

       }

 

}

 

在Demo1中设置全局Driver则需要改为:

 

========以上为环境配置和搭建内容,接下来都是使用的常见方法============

 常见使用方法 (基础篇)

1.      设置不同浏览器启动方法

System.setProperty("webdriver.ie.driver", “IE浏览器驱动文件位置”);

System.setProperty("webdriver.chrome.driver",“Chrome浏览器驱动文件位置”);

System.setProperty("webdriver.firefox.bin","FireFox浏览器位置")

 

2.      访问网页地址

driver.navigate.to(“http://www.baidu.com”)

driver.get(“http://www.baidu.com”)

 

3.      访问上一个访问的页面

driver.navigate.back()

 

4.      前进到下一个页面

driver.navigate.forward()

 

5.      刷新网页

driver.navigate.refresh()

 

6.      设置浏览器窗口大小

driver.manage().window().setSize(new Dimension(1920,1080))

 

7.      获取页面标题栏内容属性

driver.getTitle()

 

8.      获取页面源代码

driver.getPageSource()

 

9.      获取当前URL地址

driver.getCurrentURL()

 

10.   在输入框中输入指定内容

WebElement inputBox=driver.findElement(by.id(“kw”)) //百度首页文本框

inputBox.sendKeys(“Hello Selenium”)

 

11.   在输入框中清除内容

inputBox.clear()

 

12.   单击按钮

WebElement searchBox=driver.findElement(by.id(“su”)) //百度首页搜索按钮

searchBox.click()

 

13.   双击按钮

WebElement inputBox =driver.findElement(by.id(“kw”))//百度首页文本框

Actions builder = new Actions(driver) //声明actions对象

builder.doubleclick(inputBox).build().perform()

 

14.   获取控件文字内容

inputBox.getText()

 

15.   判断下拉列表是否可多选

Selectdroplist = new Select(driver.findElement(by.name(“fruit”))

droplist.isMultiple()

 

16.   操作下拉列表

droplist.getFirstSelectedOption() //选中当前下拉列表第一个选中的项

droplist.selectByIndex(3) //选中下拉列表第四个选项,从0开始

droplist.selectByValue(“Alo”) //选中下拉列表为Alo的选项

droplist.selectByVisibleText(“But”) //选中下拉列表文字为”But”的选项

 

17.   判断文字内容是否符合预期(断言,Checkpoint)

Assert.assertEqual(百度一下,你就知道 ,//预期内容“driver.getTitle(“http://www.baidu.com”)”//实际内容)

//判断百度首页标题内容是不是 “百度一下,你就知道”

 

 

18.   操作多选的选择列表

Selectdroplist = new Select(driver.findElement(by.name(“fruit”))

droplist.selectByIndex(3) //选中多选列表第四个选项,从0开始

droplist.selectByValue(“Alo”) //选中多选列表为Alo的选项

droplist.selectByVisibleText(“But”) //选中多选列表文字为”But”的选项

 

droplist.deselectByIndex(3)//取消选中多选列表第四个选项,从0开始

droplist.deselectByValue(“Alo”)//取消选中多选列表为Alo的选项

droplist.deselectByVisibleText(“But”)//取消选中多选列表文字为”But”的选项

 

19.   操作单选框

WebElement radioOption = driver.findElement(by.xpath(“//input[@value=’berry’]”))//找到value名为berry的单选框

radioOption.isSelected() //是否能被选中

 

List<WebElements> fruit =driver.findElements(by.name(“fruit”))

//把name为fruit的内容存储到List容器中,这里需要findElements

 

for (WebElement aa:fruit ) { //定义aa为遍历fruit数组

       if(aa.getAttribute(“value”).equals(“berry”)){

//如果aa找到value值里为berry的则点击

              aa.click()

}

}

20.   操作复选框

WebElement checkOption = driver.findElement(by.xpath(“//input[@value=’banna’]”))//找到value名为banna的复选框

checkOption.isSelected() //是否能被选中

 

List<WebElements> checks =driver.findElements(by.name(“fruit”))

//把name为fruit的内容存储到List容器中,这里需要findElements

 

for (WebElement aa: checks){ //定义aa为遍历check数组

       aa.click() //将复选框所有内容都选中

}

 

21.   杀掉浏览器进程 (了解)

WindowsUtils.tryToKillByName(“firefox.exe”) //杀掉火狐浏览器进程

WindowsUtils.tryToKillByName(“chrome.exe”) //杀掉chrome浏览器进程

WindowsUtils.tryToKillByName(“iexplore.exe”) //杀掉IE浏览器进程

 

22.   将当前浏览器的窗口截图 (了解)

File scrFile =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

try{

FileUtils.copyFile(scrFile,newFile("D:\\Selenium\\Screenshots\\a.png"));

         }

        

catch(Exception e)

{

       System.out.println(e);

}

 

23.   检查页面元素的文本内容是否出现

WebElement text =driver.findElement(By.xpath("//p[1]")); //利用xpath找到第一个p元素

        

String contentText = text.getText();

        

Assert.assertEquals("Fernando is worldchampion!", contentText); //判断两句话是否一致

Assert.assertTrue(contentText.contains("Fernando")); //是否包含Fernando

Assert.assertTrue(contentText.startsWith("Fernando"));//判断是不是以Fernando开头的

Assert.assertTrue(contentText.endsWith("champion!"));//判断是不是以champion!结尾的

 

24.   执行Javascript脚本

JavascriptExecutor js =(JavascriptExecutor) driver;

//声明一个Javascript执行器对象

        

String title =(String) js.executeScript("returndocument.title");//调用执行器对象的ExecutorScprit方法来执行脚本JavaScript脚本 return document.title

 

String ButtonText = (String) js.executeScript("var ButtonName =document.getElementById('su');return ButtonName.value" );

//document.getElementById('su')JavaScript代码,表示获取页面的搜索按钮对象

//return button.value 表示返回搜索按钮上的文字

        

25.   拖拽页面元素

WebElement draggable =driver.findElement(By.id("draggable"));

//在也面上找到iddraggtable的对象

        

for (int mc=0; mc<5  ; mc++) //向下拖动10个元素

{

       newActions (driver) .dragAndDropBy(draggable,0, 10).build().perform();//dragAndDropBy解释:(元素, (x轴), (y轴))

             

}

        

for (int alo=0 ; alo<5; alo++) //向右拖动10个元素

{

       newActions (driver).dragAndDropBy(draggable, 10, 0).build().perform();

}

 

26.   模拟键盘操作(了解)

Actions action = new Actions(driver); //声明Action

action.keyDown(Keys.CONTROL);//按下CTRL 

action.keyDown(Keys.SHIFT);//按下SHIFT 

action.keyDown(Keys.ALT);//按下ALT

 

action.keyUp(Keys.CONTROL);//松开CTRL

action.keyUp(Keys.SHIFT);//松开SHIFT

action.keyUp(Keys.ALT);//松开ALT

 

27.   模拟鼠标右键事件

Actions action = new Actions(driver); //声明Action

action.contextClick(driver.findElement(By.id("kw"))).perform();

 

28.   在指定元素上方进行悬停

WebElement link1 = driver.findElement(By.id("link1"));//找到id为link1的链接,实例化并赋给变量link1

WebElement link2 =driver.findElement(By.id("link2")); //找到id为link2的链接,实例化并赋给变量link2

 

Actions action1 = new Actions(driver); //实例化action动作的操作

action1.moveToElement(link1).perform();

 

29.   鼠标单击左键和释放的操作

WebElement div1=driver.findElement(By.id("div1"));

Actions action1 = new Actions(driver); //实例化action动作的操作

 

action1.clickAndHold(div1).perform(); //利用方法clickandhold实现长按鼠标左键

      

action1.release(div1).perform(); //利用release方法将鼠标松开

 

30.   查看页面元素属性

WebElement SearchBox =driver.findElement(By.id("kw")); //将搜索框的id实例化

SearchBox.getAttribute("value");//查看元素Value的属性

 

31.   获取元素CSS属性值

WebElement SearchButton =driver.findElement(By.id("su")); //实例化搜索按钮

 

SearchButton.getCssValue("height"); //用getCssValue获取按钮的高度

SearchButton.getCssValue("width"); //用getCssValue获取按钮的宽度

 

32.   隐式等待

driver.get("http://www.baidu.com");

        

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

//implicitlyWait方法设定查找页面元素等待时间,调用findElement方法时没有立刻

//找到定位元素会等待设定的等待时长,如果还没有找到则抛出NoSuchElementException

 

33.   常用的隐式等待

wait.until(ExpectedConditions.titleContains("10"));

//调用ExpectedConditionstitleContains方法判断页面的title属性是否包含“10

 

wait.until(ExpectedConditions.elementToBeSelected(option));

//调用ExpectedConditionselementToBeSelected方法,判断页面上的“FernandoAlonso”是否处于选中状态

 

wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@type='checkbox']")));

//调用ExpectedConditionselementToBeClickable方法,判断页面上的复选框是否处于选中状态

        

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//p")));

//调用ExpectedConditionspresenceOfElementLocated方法,判断页面上的p标签是否存在

        

WebElement p =driver.findElement(By.xpath("//p"));

wait.until(ExpectedConditions.textToBePresentInElement(p,"driver"));

//调用ExpectedConditionstextToBePresentInElement方法,判断页面上的p标签是否包含driver

 

34.   判断页面元素是否存在

WebElement SearchBox = driver.findElement(By.id("kw"));

SearchBox.isDisplayed()

 

35.   操作Javascript的Alert弹窗

Alert alert = driver.switchTo().alert();//使用driver.switchTo().alert()获取Alert(弹窗)对象

Assert.assertEquals(alert.getText() ,"这是一个alert的弹出框"); //判断弹窗的文字是否与预期的一致

 

36.   操作Javascript的Confirm弹窗

alert.accept(); //confirm弹窗的“OK

alert.dismiss(); //confirm弹窗的“取消”

 

37.   操作Javascript的Prompt弹窗

alert.sendKeys("Fernando Alonso is theWorld Champion"); //在alert弹窗中输入文字   

alert.accept(); //alert弹窗的“OK

alert.dismiss(); //alert弹窗的“取消”

 

38.   操作Frame中的页面元素

driver.switchTo().frame("leftframe");//Switch到左边的Frame

Assert.assertEquals(leftText.getText(),"This is Left side Frame");//判断左边Frame中获取P标签的文字是否与实际的匹配

driver.switchTo().defaultContent();//Switch回到默认的页面,否则无法进入其他的Frame页面

 

driver.switchTo().frame(2);//用索引的方式进入Frame,默认为0

 

39.   使用Frame中的Html源码来操作Frame

List<WebElement> frames =driver.findElements(By.tagName("frame"));

//利用tagname找到frame

 

for( WebElement frame:frames)//定义变量Frame,去变量frames数组里框架的名称

{

driver.switchTo().frame(frame);

               

if(driver.getPageSource().contains("frame")) //判断每个frameHTML源码中是不是包含frame

WebElement frm =driver.findElement(By.xpath("//p"));

Thread.sleep(6000);

Assert.assertEquals("This is Left sideFrame",frm.getText()); //判断左边Frame的文字是否匹配

Assert.assertEquals("This is Middleside Frame",frm.getText()); //判断中间Frame的文字是否匹配

Assert.assertEquals("This is Rightside Frame",frm.getText()); //判断右边Frame的文字是否匹配

                    

break; //找出指定的Frame退出for循环

}

 

40.   操作iFrame中的元素

driver.switchTo().frame("leftframe");//Switch到左边frame       

//注意:By.tagname也是寻找元素的方式,多用于寻找第一个标签,如html,body,frame,iframe可能需要用到

//By.tagname来寻找到

        

WebElement iframePage =driver.findElement(By.tagName("iframe")); //leftframe里的iframe找到

driver.switchTo().frame(iframePage);//Switch到左边frame里的iframe

 

41.   操作浏览器Cookie

driver.get("http://www.sogou.com");

        

Set<Cookie> cookies = driver.manage().getCookies();//得到当前页面下所有的cookies,并且输出它们所在的域,namevalue,有效日期和路径

Cookie newcookie = newCookie("cookiename","cookievalue");

 

for (Cookie cook : cookies)//定义变量cookcookie类型,能够输出以上定义的cookie类型

System.out.println(String.format("%s \n -> %s \n ->%s \n -> %s \n -> %s\n",cook.getDomain(),cook.getName(),cook.getValue(),cook.getExpiry(),cook.getPath()));

 //\n位换行符

 

driver.manage().deleteCookieNamed("cookiename");//删除cookiename属性实现删除cookie

driver.manage().deleteCookie(newcookie);//删除cookie对象实现删除cookie

driver.manage().deleteAllCookies();//删除所有的cookie

 

 常见使用方法 (进阶篇)

1.      使用JavaScriptExecutor单击元素

WebElement yuansu = driver.findElement(By.id("stb"))//搜狗首页搜索按钮

yuansu.isDisplayed() //元素是否能够显示正常

yuansu.isEnabled() //判断元素是不是可用状态

 

((JavascriptExecutor) driver).executeScript("arguments[0].click()",yuansu);

//执行JavascriptExecutor语句arguments[0].click()

 

//((JavascriptExecutor) driver)为实例化JavascriptExecutor对象,也可以也这样的形式表达: JavascriptExecutor js(变量名) = (JavascriptExecutor) driver ,driverWebdriver

 

// executeScript为执行js语句的方法函数

 

// ("arguments[0].click()",yuansu),这是js语句,意为yuansu需要单击,其中arguments[0]就是yuansu传递进来的参数

 

2.      在Ajax方式产生的浮动框中,单击选择包含某个关键字的选项 (实例:搜狗首页搜索框中出现的热门搜索内容,可以被点击)

List <WebElements>SogouLists = driver.findElements(By.xpath(“//*[@id="vl"]/div[1]/ul/li”))

//1. 找到搜狗首页搜索框中出现的热门搜索内容所在的元素框,并将其保存至List数组容器中

 

for ( WebElement myLists:SogouLists ) {

//2. 将所有找到的内容进行遍历

 

       if( myLists.getText().contains(“目标搜索到的内容”)) // contains意为包含

{

       myLists.click(); // 3. 如果遍历找到了目标内容,则点击它,进行搜索

}

 

}

 

3.      设置一个页面对象的属性值

JavascriptExecutor js(变量名) = (JavascriptExecutor) driver

//实例化JavascriptExecutor对象,,driverWebdriver

 

WebElement element =driver.findElement(By.id("text"));

String attributeName = “size”;

String value = “10”;

 

js.executeScript (“arguments[0].setAttribute(arguments[1],arguments[2])”,element,attributeName,value)

// setAttribute为设置对象属性方法removeAttribute为移除属性方法,也可用上述方法,但可以不传入value.

 

4.      在日期选择器上进行日期选择:

driver.navigate().to("http://jqueryui.com/resources/demos/datepicker/other-months.html");//转向日期选择器网址

WebElement TextBox =driver.findElement(By.id("datepicker"));//找到日历

TextBox.click();//单击

TextBox.sendKeys("02/29/2016")//sendkeys方法输入指定日期

 

5.      使用sendKeys方法上传一个附件文件

WebDriverWaitwait= newWebDriverWait(driver,5)//WebDriverWait创建一个显示等待,时间为5秒,driver为默认的Webdriver

 

wait.util(ExpectedConditions.elementToBeClickable(By.id("filesumbit")));

// ExpectedConditions为固定语法,elementToBeClickable则是判断是否该元素能否被点击

 

WebElement inputBox =driver.findElement(By.id("file"));

inputBox.sendKeys("D:\\Selenium\\html\\11.6\\Test.txt");

//将文件路径通过sendKeys方法输入

 

wait.until(ExpectedConditions.titleContains("Upload filesucceed!"));

//通过显示等待titleContains方法,判断页面title是否包含字符"Upload file succeed!"

 

6.      操作Web页面滚动条

JavaScriptExecutor js = (JavaScriptExecutor)driver //实例化JavaScriptExecutor对象

 

js.executeScript(“window.scrollTo(0,document.body.scrollHeight)”)

//使用Javascript的scrollTo函数和0,document.body.scrollHeight参数,并将页面拖动至最下方

 

WebElement name =driver.findElement(By.xpath("/html/body/div/div[2]/div[2]/div[3]/div[2]/div[1]/h3/a"));//利用xpath路径找到“电视剧”的元素 (在搜狗影视页面中)

 

js.executeScript ("arguments[0].scrollIntoView();",name)

//利用scrollIntoView()函数将其滚动至该页面

 

js.executeScript(“window.scrollBy(0,1000)”)  //使用scrollBy函数,让滚动条下滑1000个元素

 

7.      Robot对象模拟键盘操作

WebDriverWait wait = new WebDriverWait(driver,10); //显式等待10秒

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));//判断是否显示搜索的文本框

 

String content = “Hello Selenium”

StringSelection stringSelection = newStringSelection(content);//声明StringSelection对象,并使用传入的值content进行实例化操作

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,null); //使用Toolkit对象的setContents方法将字符串放到剪切板

 

Robot rbt = newRobot(); //实例化一个Robot对象

rbt.keyPress(KeyEvent.VK_CONTROL); //按下Control键

rbt.keyPress(KeyEvent.VK_V); //按下V键

rbt.keyRelease(KeyEvent.VK_V); //松开V键

rbt.keyRelease(KeyEvent.VK_CONTROL); //松开Control键

 

rbt.keyPress(KeyEvent.VK_TAB); //按下TAB键

rbt.keyRelease(KeyEvent.VK_TAB); //释放TAB键

 

rbt.keyPress(KeyEvent.VK_ENTER); //按下ENTER键

rbt.keyRelease(KeyEvent.VK_ENTER); //释放ENTER键       

 

8.      操作富文本框

//打开网站,搜狐邮箱:mail.sohu.com

((JavascriptExecutor)driver).executeScript(documents.getElementsByTagName(‘body’)[0].innerhtml=‘<b>邮件要发送的内容<b>’);

// documents.getElementsByTagName(‘body’)[0]获取富文本框的区域对象,

Innerhtml属性可以设定Html格式文本的内容

 

9.      高亮显示正在被操作的页面元素

WebElement SearchBox =driver.findElement(By.id("query")); //找到搜狗首页搜索文本框的元素

 

((JavascriptExecutor) driver). ("arguments[0].setAttribute('style',arguments[1]);",SearchBox,"background:yellow; border: 3px soild red;")

//使用setAttribute方法,去设置文本框的属性,设置为背景为黄色,边框为   3px和红色

 

10.   控制HTML5语言实现的视频播放器

//打开H5播放器网站:http://www.w3school.com.cn/tiy/loadtext.asp?f=html5_video_simple

 

WebElement MediaPlayer =driver.findElement(By.tagName("video")); //找到播放器

JavascriptExecutor jse = (JavascriptExecutor) driver//实例化javascriptExecutor对象

 

String playerURL = (String)jse.executeScript("returnarguments[0].currentSrc",MediaPlayer);

//利用executeScript方法可以执行javascript的语法语句,"return arguments[0].currentSrc"为了获取播放器的网址

//Tips:javascriptExecutor.exetuteScript返回的对象不是String类型,需要通过(String)进行强制转换

 

Double videoDuration = (Double)jse.executeScript("returnarguments[0].duration",MediaPlayer);

//利用executeScript方法可以执行javascript的语法语句,"return arguments[0].duration"为了获取播放视频的时间      

//Tips:javascriptExecutor.exetuteScript返回的对象不是Double类型,需要通过(Double)进行强制转换

 

 

jse.executeScript("returnarguments[0].play()",MediaPlayer);

//利用executeScript方法可以执行javascript的语法语句," return arguments[0].play()"能够点击视频并且播放

              

jse.executeScript("returnarguments[0].pause()",MediaPlayer);

//利用executeScript方法可以执行javascript的语法语句," return arguments[0].pause()"能够暂停视频

 

11.   在HTML5的画布元素上进行绘画操作

//打开制定网址 http://www.w3school.com.cn/tiy/loadtext.asp?f=html5_canvas_line

 

JavascriptExecutor jse = (JavascriptExecutor)driver;        //实例化JavaScriptExecutor对象

        

jse.executeScript("var canvas =document.getElementById('myCanvas');"

              +"varcxt = canvas.getContext('2d');"

              +"cxt.fillStyle= 'blue';"

              +"cxt.fillRect(0,0,150,150);");

                       

//var canvas = document.getElementByid('myCanvas');负责找到myCanvas元素,并给变量canvas

//var cxt = canvas.getContext('2d');设定画布为2d

//cxt.fillStyle = '#FF0000'; 将画布的颜色设定为红色

//cxt.fillRect(0,0,150,150); 在画布上绘制矩形

 

12.   将11小节的内容进行截图,然后保存到指定目录

File captureScreenFile =null;

 

captureScreenFile =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  //截图方法

 

FileUtils.copyFile(captureScreenFile,newFile("D://Selenium//Screenshots//canvans_pic.jpg")); 

//将截图复制指定文件夹进行保存

 

13.   操作HTML5的存储对象

String localStorage ="http://www.w3school.com.cn/tiy/loadtext.asp?f=html5_webstorage_local";

//存储网址A的对象

 

String SessionStorage ="http://www.w3school.com.cn/tiy/loadtext.asp?f=html5_webstorage_session";

//存储网址B的对象

 

JavascriptExecutor jse = (JavascriptExecutor)driver //实例化JavascriptExecutor对象

 

String lastname = (String)jse.executeScript("returnlocalStorage.lastname;"); //获取存储在localStorage中的lastname的值

 

jse.executeScript("localStorage.clear()");//清除localStorage的值

 

String lastname2 = (String)jse.executeScript("returnSessionStorage.lastname;"); //获取存储在SessionStorage中的lastname的值

 

jse.executeScript("SessionStorage.clear()"); //清除SessionStorage的值


l  2017年新更新内容:

1.      关于Selenium 3 的新特性(自己知道的)

a)      selenium-server.jar包在3.0后被删除,因为RC (Remote Control)被移除了

b)     Firefox浏览器有驱动独立,geckodriver

启动代码:

System.setproperty("webdriver.gecko.driver",独立驱动路径);

driver = new FirefoxDriver();

c)      IE最低支持版本为IE9

d)     最低java支持版本为jdk 1.8

 

2.      获取当前系统类型

String CurrentOS = System.getproperty(“os.name”);

If (CurrentOS.contains(“Win”)){

       If(CurrentOS== “Windows 7”){

              //这是Windows 7系统

}

 

else if (CurrentOS== “Windows8.1”){

              //这是Windows 8.1系统

}

 

else if (CurrentOS== “Windows 10”){

              //这是Windows 10系统

}

 

 

       //这是Windows系统

}

 

else if (CurrentOS.contains(“Mac”)){

       //这是苹果Mac OS X系统

}

 

3.      支持Windows 10的Edge浏览器

下载Webdriver的Edge驱动: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

启动代码:

System.setproperty("webdriver.EDGE.driver",驱动路径);

driver = new EdgeDriver();

 

4.      启动苹果系统Safari浏览器

Selenium 3支持Safari 10以上的浏览器。不需要独立驱动,会根据Safari安装路径找到其驱动路径

需要在浏览器设置,才能实现Safari浏览器的自动化:

a)      Safari> Preferences > Adavanced 在Show Develop menu前打勾

b)     勾选 Develop > Allow Remote Automation即可

启动代码:

driver = new SafariDriver();

 

5.      提升和优化

1)      选取浏览器驱动时尽可能都选择32位驱动。若是64位驱动,在IE浏览器上会出现输入速度慢,Firefox浏览器可能会无法正常启动

2)      在苹果Safari浏览器中,单击事件click()可能无法正常生效。可以用JavaScript脚本代替执行。例如:

WebElement SearchButton = driver.findElement(by.id(“stb”));

JavaScriptExecutor jse = newJavaScriptExecutor(driver);

jse.executeScript(“arguments[0].click()”, SearchButton)

 

SearchButton.click() 效果是一样的

同理: jse.executeScript (“returndocument.title”)与SearchButton.getTitle()也是一样的。 作用是能给获取当前网页的标题名称

3)      Jar包路径更换为相对路径更佳:

Selenium的jar包是必不可少的,此前的做法是将其放置在独立于项目Project之外的文件夹中。这样做如果换到其他电脑上,项目无法识别到指定路径的jar包,会报错。现在可以将其放在项目内新建一个文件夹放置其中,然后再导入。这样换了电脑,从Windows系统换到Mac系统也不会出错。能够在多台电脑上运行。

 

6.      关于IE的一些坑

a)      将网页缩放比例设置为100%

如果设置为非100%,会出现报错,需将浏览器网页缩放比例设置为100%才能保证浏览器能够正常运行

b)     启用保护模式

打开IE浏览器 à Internet选项 à 安全 在“安全”的标签卡中,选择所有的安全区域,将“启用保护模式”勾选,否则也会出现运行错误

c)      IE11在Windows系统将无法启动

除了完成上述两点,还需要在注册表中进行设置:

32位:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InternetExplorer\Main\FeatureControl\FEATURE_BFCACHE

64位:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE

如果FeatureControl下没有FEATURE_BFCACHE,就以FEATURE_BFCACHE为名新建一个项。并在其下创建一个DWORD,取名为:iexplore.exe,value为0

设置完成后,重启计算机以生效,在IE11以下版本的浏览器不需要在注册表中进行设置

实例代码:https://github.com/John0731/MySeleniumCase

猜你喜欢

转载自blog.csdn.net/qq_41030861/article/details/80986411
今日推荐