java selenium使用

注意:一定要搞清楚,你的系统是win64还是32的,然后下载相应版本的selenium-server-standalone-3.3.x.jar和selenium-java-3.3.x.zip,要不然会报各种错误,你还不知道该怎么解决的。。。。 [蜜汁微笑]

下面说明一下java编程的步骤:
1.下载使用到材料
点击这里下载各种版本的jar
把相应的driverServer.exe放入浏览器的安装目录下,比如:IEDriverServer.exe放入本地磁盘C:\Program Files\Internet Explorer目录下


2.eclipse中创建普通工程
创建java工程,selenium-java-3.3.x.zip解压,把lib直接拷到工程目录下,把client-combined-3.3.1-nodeps.jar拷进lib中,build path把jar包加入工程中。
创建类,编程。
3.eclipse中创建maven工程
创建maven工程,在pom.xml文件中,增加依赖,我用的3.4.0版本:
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>
1
2
3
4
5
4.获取driver
IE
System.setProperty( "webdriver.ie.driver" ,"C:/Program Files/Internet Explorer/IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
capabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
1
2
3
4
5
6
Google
System.setProperty ( "webdriver.chrome.driver" , "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe" );
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
options.addArguments("no-sandbox");
//options.addArguments("headless");  //不打开浏览器
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(options);
1
2
3
4
5
6
7
8
9
10
5.定位元素
基础定位方法:

方法    举例    说明
By.id    WebElement element = driver.findElement(By.id(“appId”));    通过元素ID定位
By.name    WebElement element = driver.findElement(By.name(“app”));    通过元素name定位
By.className    List< WebElement> elements = driver.findElements(By.className(“app”));    通过class定位
By.tagName    List< WebElement> elements = driver.findElements(By.tagName(“input”));    通过标签名称定位
By.linkText    WebElement element = driver.findElement(By.linkText(“百度”));    通过链接的文字定位。例如:`< a href=“www.baidu.com”>百度</ a>
By.partialLinkText    WebElement element = driver.findElement(By.partialLinkText(“百度”));    通过链接字模糊定位。如果一个有文字链接的元素,上面文字太多,不想写这么多文字,那么就可以用PartialLinkText,也就是用LinkText里面的一部分字符就可以定位该元素。选取的字符要有唯一性,也就是根据你选取的字符,在当前页只能找到你的目标元素。
重要定位方法:
By.xpath

xpath定位方法    举例
利用元素属性定位    WebElement element = driver.findElement(By.xpath("//input[@onclick=‘Open_tab(2)’]"));
绝对路径定位    WebElement wElement = driver.findElement(By.xpath("/html/body/div/form/input"))
相对路径    WebElement wElement = driver.findElement(By.xpath("//form/span/input"))
级与属性结合    WebElement wElement = driver.findElement(By.xpath("//span[@class=‘bg s_ipt_wr iptfocus quickdelete-wrap’]/input"))
使用逻辑运算符    WebElement wElement = driver.findElement(By.xpath("//input[@class=‘s_ipt’ and @id=‘kw’]"))
模糊查找    driver.findElement(By.xpath("//input[contains(@onclick,‘TTmoasAppTmxzAppform’)]")).sendKeys(Keys.ENTER)
By.cssSelector
根据tagName:driver.findElement(By.cssSelector(“input”)
根据ID:driver.findElement(By.cssSelector(“input#username”));//html标签和id
参考:cssSelector之selenium元素定位

6.执行javascript代码
((JavascriptExecutor)driver).executeScript("isOpen(2)");

7.显式等待元素
如果在页面找不到id为code元素,显式等待code的元素最多10秒时间,如果10秒后还没获取到code元素则抛出异常

WebDriverWait wait = new WebDriverWait(driver, 10);//等待元素10秒
wait.until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver d){
        boolean loadcomplete=driver.findElement(By.id("code")).isDisplayed();
        return loadcomplete;
    }
});
1
2
3
4
5
6
7
8.其他
操作下拉列表
下拉列表的id为appdq:

Select select = new Select(driver.findElement(By.id("appdq")))
select.selectByVisibleText("A");//选择A
select.selectByValue("1"); 
select.deselectAll();
select.deselectByValue("1");
select.deselectByVisibleText("A");
select.getAllSelectedOptions();
select.getFirstSelectedOption(); 
1
2
3
4
5
6
7
8
关闭浏览器
driver.close();//关闭当前的浏览器窗口
driver.quit();//不仅关闭了当前的浏览器窗口还彻底的退出WedDriver,释放了Driver与Server之间的链接
1
2
建议使用driver.quit()。

上传文件
WebElement element =driver.findElement(By.id("file"));
String filePath = "C:\\a.txt";
element .sendKeys(filePath);
1
2
3
切换iframe,Windows
driver.switchTo().defaultContent();//返回到最顶层的frame/iframe
driver.switchTo().frame("frame0");//切换到某个frame:
driver.switchTo().window("window"); //切换到某个window 

Set<String> handlers=driver.getWindowHandles();//获取所有窗口
String currHandle=driver.getWindowHandle();//获取当前窗口
for(String s:handlers){
    if (!s.equals(currHandle)) {
        driver.switchTo().window(s);//切换到其他窗口
    }
}
1
2
3
4
5
6
7
8
9
10
11
click()点击无效,sendKeys()输入数据少字
可以尝试执行JavaScript代码的方式解决,
代码1:

driver.findElement(By.id("share1")).click();
1
改为:

((JavascriptExecutor)driver).executeScript("document.getElementById('share1').click();");
1
代码2:

driver.findElement(By.id("sex")).sendKeys((user.getSex()).toUpperCase());
1
改为:

String sex="document.getElementById('sex').value='"+user.getSex()+"';";
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(sex);
1
2
3
页面元素不可编辑
类似这种,设置元素为readOnly

通过执行js代码,删除readOnly属性

((JavascriptExecutor)driver).executeScript("document.getElementById('apporregNum').removeAttribute(\"readOnly\");");
1
获取不到某个元素
有时程序执行太快,网页还没加载完毕,这时需要在代码中让线程休息几秒钟Thread.sleep(2000);,有好多次出错都是因为执行太快了。

编程过程中注意事项
1.对异常的处理,对每个元素执行一次操作就进行异常捕获,防止抛出异常导致程序无法继续执行;
2.如果要获取页面上的数据,可以使用jsoup,或者是selenium+jsoup;

 driver.get(INDEX_URL);//打开浏览器,访问网址
 String pageSource = driver.getPageSource();
 Document doc = Jsoup.parse(pageSource);
 doc.select("#mainsrp-itemlist .item");//#对应的id,.对应class
1
2
3
4
3.httpunit
4.执行js代码时对单引号或双引号的需要转义

String nameCn = "I'm a girl".replaceAll("'", "\\\\'");//将单引号转义为\'
String appCnName="document.getElementById('appCnName').value='"+nameCn+"';";
js.executeScript(appCnName);
1
2
3
等待补充
--------------------- 
作者:格格_ 
来源:CSDN 
原文:https://blog.csdn.net/qq_23888451/article/details/70161097 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_41508948/article/details/88095320