selenium java 浏览器操作
环境搭建
selenium 2.53
selenium-java-2.53.0.jar
selenium-java-2.53.0-srcs.jar 原代码包
拷贝的工程lib下,做build path,告诉项目jar包在lib里
关联原始代码:
jar包里都是.class文件,想看原始代码,关联源代码包,在selenium项目包右键属性,选java source attachment,选择selenium-java-2.53.0-srcs.jar。
package com.thoughtworks.selenium 源代码
package org.openqa.selenium 开源的代码
一个driver是一个浏览器实例,
selenium2.4.5-javadoc/index.html: api文档
-org.openqa.selenium.firefox 存放的是Firefox浏览器使用的类
- --FirefoxBinary
- --FirefoxDriver 浏览器实例
- --FirefoxProfile 用户配置文件
构造方法重载:不同的方式构造实例
FirefoxDriver()
FirefoxDriver(Capabilities desiredCapabilities)
FirefoxDriver(Capabilities desiredCapabilities, Capabilities requiredCapabilities)
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile)
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities capabilities)
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities desiredCapabilities, Capabilities requiredCapabilities)
FirefoxDriver(FirefoxProfile profile)
package test.selenium; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumTest { public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://nvsm.cnki.net/KNS/");
driver.close();
}
}
如果出现打不开浏览器,地址栏不能输入,操作不了页面dom,都是selenium版本和浏览器版本不匹配。selenium更新版本比浏览器慢,不能保证支持最新的浏览器版本。selenium2.53可以支持Firefox40以下版本。
Webdriver基础API - 浏览器实例管理
- -org.openqa.selenium.ie
- --InternetExplorerDriver
- org.openqa.selenium.chrome
- --ChromeDriver
- public class FirefoxDriver extends RemoteWebDriver
public class RemoteWebDriver extends java.lang.Object implements WebDriver - 如果需要用的Firefox特殊的方法,需强制类型转换
- appium和selenium用的是一套webdriver协议(多态)
- 执行程序每次打开的都是一个全新的没有设置的Firefox浏览器,设置不会在下次生效。selenium只会在默认路径(C:\Program Files (x86)\Mozilla Firefox\firefox.exe)找Firefox,如果安装位置不在默认路径则会报找不到Firefox可执行文件的错误。
- 举例:让selenium找的Firefox安装位置
System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://nvsm.cnki.net/KNS/");
举例:构造浏览器实例
FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile)
FirefoxBinary(java.io.File pathToFirefoxBinary)
FirefoxBinary ffb = new FirefoxBinary(new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"));
WebDriver driver = new FirefoxDriver(ffb,null);
driver.get("http://nvsm.cnki.net/KNS/");
举例:构造浏览器实例(带配置文件的情况,利用存在的profile文件)
FirefoxProfile(java.io.File profileDir)
FirefoxProfile作用:保存用户配置信息,包括:浏览器设置信息,插件以及设置,书签和历史记录,用户名和密码,临时文件和网站数据,cookies。
cmd命令行输入:firefox.exe -ProfileManage
C:\Program Files (x86)\Mozilla Firefox>firefox.exe -ProfileManage
运行输入:%APPDATA%,打开C:\Users\PC\AppData\Roaming,所有的用户配置信息都在:C:\Users\PC\AppData\Roaming\Mozilla\Firefox\Profiles\1h1iplez.default
FirefoxProfile ffp = new FirefoxProfile(new File("C:\\Users\\PC\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\1h1iplez.default"));
WebDriver driver = new FirefoxDriver(ffp);
driver.get("http://nvsm.cnki.net/KNS/");
举例:构造浏览器实例(带配置文件的情况,自定义profile文件启动)
FirefoxProfile有3个重载的方法:
void |
setPreference(java.lang.String key, boolean value)
Set a preference for this particular profile.
|
void |
setPreference(java.lang.String key, int value)
Set a preference for this particular profile.
|
void |
setPreference(java.lang.String key, java.lang.String value)
Set a preference for this particular profile.
|
浏览器地址栏输入:about:config,设置所有的属性和插件配置
浏览器相关配置:browser
例如:设置启动默认页面:browser.startup.homepage
FirefoxProfile ffp = new FirefoxProfile();
ffp.setPreference("browser.startup.homepage", "http://nvsm.cnki.net/KNS/"); //设置启动页
ffp.setPreference("browser.startup.page", ); //0空白首页设置不生效 1用户自定义首页
WebDriver driver = new FirefoxDriver(ffp);
Webdriver设置Firefox无提示默认路径下载
FirefoxProfile ffp = new FirefoxProfile();
ffp.setPreference("browser.download.dir", "C:\\");
ffp.setPreference("browser.download.folderList", );
// 设置浏览器默认下载文件夹 0桌面 1我的下载 2自定义
ffp.setPreference("browser.download.manager.showWhenStarting", false);
ffp.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream, application/vnd.ms-excel, text/csv, application/zip");
WebDriver driver = new FirefoxDriver(ffp);
firebug插件,网络查看资源包括静态资源和js代码加载快慢,刷新地址可生成网络布图,资源加载的时间,参数可以输出成har文件,可以用showslow打开
举例:自动收集页面加载时序图
FirefoxProfile ffp = new FirefoxProfile();
ffp.addExtension(new File("source\\firebug-2.0.17.xpi"));
ffp.addExtension(new File("source\\netExport-0.8.xpi"));
// 插件相关
ffp.setPreference("extensions.firebug.allPagesActivation", "on"); //所有页面自动开启
ffp.setPreference("extensions.firebug.net.enableSites", "true"); //网络设置成开启
ffp.setPreference("extensions.firebug.defaultPanelName","net");
ffp.setPreference("extensions.firebug.netexport.alwaysEnableAutoExport","true");
ffp.setPreference("extensions.firebug.netexport.saveFiles","true");
ffp.setPreference("extensions.firebug.netexport.defaultLogDir", "C:\\");
WebDriver driver = new FirefoxDriver(ffp);
Thread.sleep();
driver.get("http://nvsm.cnki.net/KNS/");
Driver常用方法(浏览器相关操作)
与导航地址栏相关:
get 地址栏输入地址:driver.get("http://nvsm.cnki.net/kns/brief/result.aspx?dbprefix=CJFQ");
网页的资源都加载完毕,selenium捕获网页状态,都加载完成方法结束,未加载完会等待默认等待60s,仍未加载完成会向上抛出页面加载超时的异常。
navigate
back 回退
forward 前进
to 和driver.get()效果差不多,get更成熟
fresh 刷新
getCurrentUrl 尽量不用页面某个ui元素作为验证点
getPageSource 获取网页的原始代码
driver.get("http://nvsm.cnki.net/KNS/");
System.out.println(driver.getPageSource());
Pattern p = Pattern.compile("<a.*/a>");
Matcher m = p.matcher(driver.getPageSource());
while(m.find())
{
String aa = m.group();
// System.out.println(aa);
String[] ss = aa.split("\"");
for(String s:ss)
{
if(s.contains("http://"))
{
System.out.println(s);
driver.get(s);
Thread.sleep();
}
}
}
}
getTitle 相对用的较少
manage driver.manage() 返回值类型是Options:
driver.manage().addCookie(cookie); driver.manage().window().maximize(); driver.manage().window().fullscreen(); System.out.println(driver.manage().window().getSize().height); System.out.println(driver.manage().window().getSize().width); driver.manage().window().setSize(new Dimension(,)); driver.manage().timeouts(); //脚本执行超时限制
quit/close
quit 断掉http会话
close 关闭当前浏览器打开窗口
查询页面元素
driver.findElement(By):查询单个对象,查询了多个则selenium返回第一个对象
通过id:前端页面可以没有页面元素,有元素就是唯一的id,不会重复
通过Name:Name属性可以重复
通过className:class属性的值,class是给页面一批元素添加一类class属性
通过LinkText:<a href>和</a>之间的内容
通过PartialLinkText:部分文本值
通过XPATH:
通过CSS选择器(忽略)
通过TagName:可以用TagName先缩小范围
组合-连续查找:在findElement找的元素之后,在子元素下继续查询元素,缩小范围
复合元素以及多对象定位:driver.findElements(By)
方法的返回值类型为webElement对象的list(集合形式)
xpath参考:http://www.w3school.com.cn/xpath/index.asp
操作页面元素
基本控件的调用方法:
输入框:input -- sendkeys
clear
<input id="user" type="text"> input 标签
id 属性
user 属性值
type 属性
text 属性值
FirefoxProfile ffp = new FirefoxProfile();
ffp.setPreference("browser.startup.homepage", "http://nvsm.cnki.net/KNS/"); //设置启动页
ffp.setPreference("browser.startup.page", ); //0空白首页设置不生效 1用户自定义首页
WebDriver driver = new FirefoxDriver(ffp);
driver.get("http://nvsm.cnki.net/kns/brief/result.aspx?dbprefix=CJFQ");
driver.findElement(By.id("txt_1_value1")).sendKeys("期刊");
WebDriver driver = new FirefoxDriver();
driver.get("http://nvsm.cnki.net/kns/brief/result.aspx?dbprefix=CJFQ");
WebElement we = driver.findElement(By.id("txt_1_value1"));
we.click();
we.clear();
we.sendKeys("期刊");
超链接:a -- click
获取属性
<a class="baidu" target="_blank" href="https://www.baidu.com/">baidu</a> target="_blank" 每次点都打开新页签 selenium称窗口切换,selenium无法自动切换
可以取href的地址填的地址栏中,操作完再回退至之前的窗口。
WebElement we1 = driver.findElement(By.linkText("新型出版模式介绍"));
we1.click();
WebElement we2 = driver.findElement(By.partialLinkText("导航"));
we2.click();
WebElement we2 = driver.findElement(By.partialLinkText("导航"));
System.out.println(we2.getAttribute("href"));
String daohang = we2.getAttribute("href");
driver.get(daohang);
Thread.sleep();
driver.navigate().back();
下拉菜单:select
WebElement we3 = driver.findElement(By.id("txt_1_sel"));
Select select = new Select(we3);
List<WebElement> list = select.getOptions();
for(int i = ;i<list.size();i++)
{
WebElement we4 = list.get(i);
we4.click();
Thread.sleep();
}
select.selectByVisibleText("全文");
Thread.sleep();
select.selectByValue("DOI$=|??");
int num = list.size();
int random = new Random().nextInt(num);
select.selectByIndex(num);
单选:radiobox
多选:checkbox -- click
isSelected
List<WebElement> list = driver.findElements(By.xpath("/html/body/form/div[4]/div[2]/div/dl/dd/dl/dd[4]/input"));
System.out.println(list.size());
for(int i=;i<list.size();i++)
{
list.get(i).click();
Thread.sleep();
System.out.println(list.get(i).getAttribute("id"));
System.out.println(list.get(i).isSelected());
}
button -- click
isEnable :判断页面的按钮是否是可点击的
有可能自动化和手动点击的操作不同,询问能否绕过选择其他方式(回车,提交的接口,触发链接,js,浏览器刷新)。
获取对象属性或文本值
getAttribute() 取属性名称
getText() 取文本值
WebDriver driver = new FirefoxDriver();
driver.get("http://www.huicewang.com/ecshop/"); driver.manage().window().maximize();
//切换精品推荐页签
List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"itemBest\"]/h2/a"));
for(WebElement we:elements)
{
we.click();
Thread.sleep();
//取各页签中商品价格
List<WebElement> prices = driver.findElements(By.xpath("//*[@id=\"show_best_area\"]/div[@class=\"goodsItem\"]/font"));
System.out.println(prices.size());
for(WebElement price:prices)
{
System.out.println(price.getText());
}
//取商品的图片地址
List<WebElement> photos = driver.findElements(By.xpath("//*[@id=\"show_best_area\"]/div[@class=\"goodsItem\"]/a/img"));
for(WebElement photo:photos)
{
System.out.println(photo.getAttribute("src"));
}
}
用java.net包发http请求,检查地址返回值是否是200,保证展示正确。
高级应用
事件操作
Actions类:
位置:org.openqa,selenium.interactions.Actions
作用:
selenium java 浏览器操作的更多相关文章
- selenium控制浏览器操作
selenium控制浏览器操作 控制浏览器有哪些操作? 控制页面大小 前进.后退 刷新 自动输入.提交 ........ 控制页面大小,实例: # -*- coding:utf-8 -*- from ...
- 《手把手教你》系列技巧篇(二十六)-java+ selenium自动化测试-浏览器操作(详细教程)
1.简介 在Web自动化的操作中,我们通常需要使用一些方法来操作浏览器,今天就来学习一下.这一篇宏哥主要是介绍一下,在自动化测试的时候,我们常见的一些浏览器操作有哪些,宏哥将会一一介绍和讲解. 2.浏 ...
- python3 scrapy 使用selenium 模拟浏览器操作
零. 在用scrapy爬取数据中,有写是通过js返回的数据,如果我们每个都要获取,那就会相当麻烦,而且查看源码也看不到数据的,所以能不能像浏览器一样去操作他呢? 所以有了-> Selenium ...
- selenium 常用浏览器操作API
package test; import org.openqa.selenium.By;import org.openqa.selenium.Dimension;import org.openqa.s ...
- Selenium+java - 截图操作
写在前面 自动化测试过程中,运行失败截图可以很好的帮我们定位问题,因此,截图操作也是我们自动化测试中的一个重要环节. 截图方法 1.通过截图类TakeScreenshout实现截图 特点:截取浏览器窗 ...
- selenium(java)浏览器多窗口切换处理
要在多个窗口直接切换,首先获取每个窗口的唯一标示符(句柄),通过窗口属性可以获取所有打开窗口的标示符,以集合的形式返回:以下示例: Set<String> winHandels ...
- python下selenium模拟浏览器基础操作
1.安装及下载 selenium安装: pip install selenium 即可自动安装selenium geckodriver下载:https://github.com/mozilla/ge ...
- selenium+Java使用内容记录(全)
1.模拟键盘操作,使用enter键 2.等待几秒 3.浏览器最大化 4.获取cookie,删除cookie 5.模拟鼠标 6.selenium+java 识别验证码(数字+字母组合) 7.seleni ...
- Selenium常用API的使用java语言之7-控制浏览器操作
(六)控制浏览器操作 1.控制浏览器窗口大小 有时候我们希望能以某种浏览器尺寸找开,访问的页面在这种尺寸下运行.例如可以将浏览器设置成移动端大小(480* 800),然后访问移动站点,对其样式进行评估 ...
随机推荐
- LAB1 partI
序言 1. master.go 可以正常调用Distributed() 和 Sequential(). Sequential 顺序执行主要用于调试. 2. master : 创建一个 RPC serv ...
- global的使用
对于一个全局变量,你的函数里如果只使用到了它的值,而没有对其赋值(指a = XXX这种写法)的话,就不需要声明global. 相反,如果你对其赋了值的话,那么你就需要声明global.声明global ...
- [转]TopShelf 用法
static void Main(string[] args) { { x.Service<SyncData>(s => { s.ConstructUsing(name => ...
- 01-使用eclipse新建一个标准的 java web项目
1.使用eclipse创建个普通的Java SE项目 名称:CRM java web标准目录结构 crm WEB-INF classes lib web.xml 设置项目字节码输出目录
- oracle存储过程和存储函数&触发器
oracle存储过程和存储函数 指存储在数据库中供所有用户程序调用的子程序叫存储过程,存储函数 存储过程和存储函数的相同点:完成特定功能的程序 存储过程和存储函数的区别:是否用return语句返回值 ...
- FastSocket客户端/服务端通讯示例 客户端被动接收
示例代码参见 http://www.cnblogs.com/T-MAC/p/fastsocket-asyncbinary-usage.html 我这里只写一份客户端如何被动接收的代码. 先从As ...
- java+Selenium+TestNg搭建自动化测试架构(2)实现跨浏览器功能
1.切换浏览器类:其中包含了切换浏览器的方法,以及关闭浏览器,设置等待时间,以及重写的断言方法 package com.rrx.framework; import java.io.IOExceptio ...
- js 连接mqtt
js连接mqtt 项目中要用到mqtt,前端调用,使用github开源的paho-mqtt.js,api还是挺全面的,网上各种教程很全面,但是感觉代码过于杂乱,故而封装的一下.仿jquery ajax ...
- sql语句case when 以及left()
select count(CASE jyje WHEN '1300' THEN '2' ELSE '1' END) as count from tpent_orders where cplx = 6 ...
- 数据库新增“自动添加”类字段 auto_now_add 如何不影响之前数据
django 中的模版为例:time = models.DateTimeField('创建时间', auto_now_add=True)这样显然是不行的.那么.我们可以考虑先给前面数据一个默认值迁移一 ...