环境搭建

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浏览器使用的类

构造方法重载:不同的方式构造实例

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

Actions(WebDriver driver)

作用:

selenium java 浏览器操作的更多相关文章

  1. selenium控制浏览器操作

    selenium控制浏览器操作 控制浏览器有哪些操作? 控制页面大小 前进.后退 刷新 自动输入.提交 ........  控制页面大小,实例: # -*- coding:utf-8 -*- from ...

  2. 《手把手教你》系列技巧篇(二十六)-java+ selenium自动化测试-浏览器操作(详细教程)

    1.简介 在Web自动化的操作中,我们通常需要使用一些方法来操作浏览器,今天就来学习一下.这一篇宏哥主要是介绍一下,在自动化测试的时候,我们常见的一些浏览器操作有哪些,宏哥将会一一介绍和讲解. 2.浏 ...

  3. python3 scrapy 使用selenium 模拟浏览器操作

    零. 在用scrapy爬取数据中,有写是通过js返回的数据,如果我们每个都要获取,那就会相当麻烦,而且查看源码也看不到数据的,所以能不能像浏览器一样去操作他呢? 所以有了-> Selenium ...

  4. selenium 常用浏览器操作API

    package test; import org.openqa.selenium.By;import org.openqa.selenium.Dimension;import org.openqa.s ...

  5. Selenium+java - 截图操作

    写在前面 自动化测试过程中,运行失败截图可以很好的帮我们定位问题,因此,截图操作也是我们自动化测试中的一个重要环节. 截图方法 1.通过截图类TakeScreenshout实现截图 特点:截取浏览器窗 ...

  6. selenium(java)浏览器多窗口切换处理

    要在多个窗口直接切换,首先获取每个窗口的唯一标示符(句柄),通过窗口属性可以获取所有打开窗口的标示符,以集合的形式返回:以下示例:       Set<String> winHandels ...

  7. python下selenium模拟浏览器基础操作

    1.安装及下载 selenium安装: pip install selenium  即可自动安装selenium geckodriver下载:https://github.com/mozilla/ge ...

  8. selenium+Java使用内容记录(全)

    1.模拟键盘操作,使用enter键 2.等待几秒 3.浏览器最大化 4.获取cookie,删除cookie 5.模拟鼠标 6.selenium+java 识别验证码(数字+字母组合) 7.seleni ...

  9. Selenium常用API的使用java语言之7-控制浏览器操作

    (六)控制浏览器操作 1.控制浏览器窗口大小 有时候我们希望能以某种浏览器尺寸找开,访问的页面在这种尺寸下运行.例如可以将浏览器设置成移动端大小(480* 800),然后访问移动站点,对其样式进行评估 ...

随机推荐

  1. note10 元组

    元组 Tuple +元组即不可变(immutable)列表 除了可改变列表内容的方法外,其他方法均适用于元组 因此,索引.切片.len().print等均可用 但是,appeng.extend.del ...

  2. 前端使用crypto.js进行加密

    前端使用crypto.js进行加密 https://www.cnblogs.com/lz2017/p/8046816.html   最近我在前端使用Cookies保存密码的时候需要前端来进行加密工作, ...

  3. 性能测试过程中oracle数据库报ORA-27301 ORA-27302错

    最近在性能测试过程中发现,发现虚拟用户数上不去,加载到一定的数量应用端就报错,提示连接数据库出错.在测试的过程中查看web容器的线程池 数据源的连接池 都还有空闲,同时查看oracle的v$sessi ...

  4. numpy linalg

    线性代数 np.mat("0 1 0;1 0 0;0 0 1") np.linalg.inv(A)

  5. <<让你自己的APP成为系统应用>>所遇到的问题及解决方法

    1.adb connect 10.100.1.772.adb -s 10.100.1.77 shell remount3.让你自己的APP成为系统应用 adb push xxx.apk system/ ...

  6. 三、CSS样式——列表

    概念: CSS列表属性允许你放置.改变列表标志,或者将图像作为列表项标志 属性 描述 list-style 简写列表项 list-style-image 列表项图像 list-style-positi ...

  7. Spring3.2.0 之后各个版本完整包下载地址

    留作工作学习使用 现在Spring官网已经很难找到完整包的下载地址,都已经迁移到Maven上,这给不能用Maven或者不愿用Maven的各位带来了不小的麻烦. 经过挖掘,找到了下载3.2之后各个版本完 ...

  8. anaconda安装Opencv报错:Could NOT find PythonLibs: Found unsuitable version "2.7.6",

    机器上装了两个python,一个是默认的,一个是anaconda.安装opencv时就报错了: -- Found PythonInterp: /home/deeplp/anaconda2/bin/py ...

  9. Django11-ModelForm

    一.定义ModelForm类 # 创建部门表单校验 class DepartmentForm(forms.ModelForm): class Meta: model = models.Departme ...

  10. list之flex布局写法

    list之flex布局写法 移动端实际场景中经常会遇到将header置顶,然后下面list需要滚动的情况,通常的做法会是将header使用fixed的方式固定到顶部,然后list主体相对于header ...