【javawb】【页面元素的的操作】

1. 输入框(text field or textarea)

 找到输入框元素:

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

在输入框中输入内容:

element.sendKeys(“test”);

将输入框清空:

element.clear();

获取输入框的文本内容:

element.getText();

 

2. 下拉选择框(Select)

找到下拉选择框的元素:

Select select = new Select(driver.findElement(By.id("select")));

 

选择对应的选择项:

select.selectByVisibleText(“mediaAgencyA”);

select.selectByValue(“MA_ID_001”);

 

不选择对应的选择项:

select.deselectAll();

select.deselectByValue(“MA_ID_001”);

select.deselectByVisibleText(“mediaAgencyA”);

或者获取选择项的值:

select.getAllSelectedOptions();

select.getFirstSelectedOption();

 

对下拉框进行操作时首先要定位到这个下拉框,new 一个Selcet对象,然后对它进行操作 

3. 单选项(Radio Button)

找到单选框元素:

WebElement bookMode =driver.findElement(By.id("BookMode"));

选择某个单选项:

bookMode.click();

清空某个单选项:

bookMode.clear();

判断某个单选项是否已经被选择:

bookMode.isSelected();

4. 多选项(checkbox)

多选项的操作和单选的差不多:

WebElement checkbox =driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

5. 按钮(button)

找到按钮元素:

WebElement saveButton = driver.findElement(By.id("save"));

点击按钮:

saveButton.click();

判断按钮是否enable:

saveButton.isEnabled ();

6. 左右选择框

也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如:

Select lang = new Select(driver.findElement(By.id("languages")));

lang.selectByVisibleText(“English”);

WebElement addLanguage =driver.findElement(By.id("addButton"));

addLanguage.click();

7. 弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();

8. 表单(Form)

Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:

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

approve.click();

approve.submit();//只适合于表单的提交

9. 上传文件 (Upload File)

上传文件的元素操作:

WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));

String filePath = "C:\test\\uploadfile\\media_ads\\test.jpg";

adFileUpload.sendKeys(filePath);

10.拖拉(Drag andDrop)

WebElement element =driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

 

(new Actions(driver)).dragAndDrop(element, target).perform();

 

11.导航 (Navigationand History)

打开一个新的页面:

 driver.navigate().to("http://www.example.com");

 

通过历史导航返回原页面:

driver.navigate().forward();

driver.navigate().back();

 

 

 

iframe的处理      

                                                                                                                                 

有时候我们在定位一个页面元素的时候发现一直定位不了,反复检查自己写的定位器没有任何问题,代码也没有任何问题。这时你就要看一下这个页面元素是 否在一个iframe中,这可能就是找不到的原因之一。如果你在一个default content中查找一个在iframe中的元素,那肯定是找不到的。反之你在一个iframe中查找另一个iframe元素或default content中的元素,那必然也定位不到。

selenium webdriver中提供了进入一个iframe的方法:

WebDriver org.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId)

也提供了一个返回default content的方法:

WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent()

这样使我们面对iframe时可以轻松应对。

以下面的html代码为例,我们看一下处现iframe。

 

Html代码

 

main.html

 

<html>

    <head>

        <title>FrameTest</title>

    </head>

    <body>

<div id = "id1">this is a div!</div>

        <iframe id = "frame"  frameborder="0" scrolling="no" style="left:0;position:absolute;" src = "frame.html"></iframe>

    </body>

</html>

 

 

 

frame.html

 

<html>

    <head>

        <title>this is a frame!</title>

    </head>

    <body>

<div id = "div1">this is a div,too!</div>

<label>input:</label>

<input id = "input1"></input>

    </body>

</html>

 

 

Java代码

 

public class FameStudy {

public static void main(String[] args) {

WebDriver dr = new FirefoxDriver();

String url = "\\Your\\Path\\to\\main.html";

dr.get(url);

 

//在default content定位id="id1"的div

dr.findElement(By.id("id1"));

 

//此时,没有进入到id="frame"的frame中时,以下两句会报错

dr.findElement(By.id("div1"));//报错

dr.findElement(By.id("input1"));//报错

 

//进入id="frame"的frame中,定位id="div1"的div和id="input1"的输入框。

dr.switchTo().frame("frame");

dr.findElement(By.id("div1"));

dr.findElement(By.id("input1"));

 

//此时,没有跳出frame,如果定位default content中的元素也会报错。

dr.findElement(By.id("id1"));//报错

 

//跳出frame,进入default content;重新定位id="id1"的div

dr.switchTo().defaultContent();

dr.findElement(By.id("id1"));

}

 

}

 

 

小结:

switch_to方法会new1个TargetLocator对象,使用该对象的frame方法可以将当前识别的”主体”移动到需要定位的frame上去。  

【得到弹出的窗口】

在selenium 1.X里面得到弹出窗口是一件比较麻烦的事,特别是新开窗口没有id、name的时候。在selenium webdriver中得到新开窗口相对简单的多,它无关新开窗口的id、name等属性。以下面的html为例:

 

 

Html代码

 

 

<span style="white-space: normal; background-color: #ffffff;">test.html</span>

 

 

<html>

 

    <head><title>Test Popup Window</title></head>

 

    <body>

 

        <a id = "51" href = "http://www.51.com/" target = "_blank">Let's go!</a>

 

    </body>

 

</html>

 

 

下面的代码演示了如何去得到弹出的新窗口

 

Java代码

public class PopupWindowTest {

public static void main(String[] args) {

System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");  

WebDriver dr = new FirefoxDriver();

String url ="\\Your\\Path\\to\\main.html";

dr.get(url);

dr.findElement(By.id("51")).click();

//得到当前窗口的句柄

String currentWindow = dr.getWindowHandle();

//得到所有窗口的句柄

Set<String> handles = dr.getWindowHandles();

Iterator<String> it = handles.iterator();

while(it.hasNext()){

if(currentWindow == it.next())  continue;

dr.switchTo().window(it.next());

 

}

}

 

}

 

输出结果:

 

title,url = 51.com 真人配对玩游戏,http://www.51.com/

 

小结:

 

捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。(

在上面的代码里,使用windowhandle方法来获取当前浏览器窗口的句柄,使用了windowhandles方法获取所有弹出的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。

在获取新弹出窗口的句柄后,使用switchto.window(newwindow_handle)方法,将新窗口的句柄作为参数传入既可捕获到新窗口了。

如果想回到以前的窗口定位元素,那么再调用1次switchto.window方法,传入之前窗口的句柄既可达到目的。

 

【处理alert,confirm,prompt对话框

 

Html代码

 

Dialogs.html  

<html>

    <head>

        <title>Alert</title>

    </head>

    <body>

        <input id = "alert" value = "alert" type = "button" onclick = "alert('欢迎!请按确认继续!');"/>

  <input id = "confirm" value = "confirm" type = "button" onclick = "confirm('确定吗?');"/>

<input id = "prompt" value = "prompt" type = "button" onclick = "var name = prompt('请输入你的名字:','请输入

你的名字'); document.write(name) "/>

    </body>

</html>

 

 

 以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字 。

 

selenium webdriver 处理这些弹层的代码如下:

 

Java代码

 

public class DialogsStudy {

public static void main(String[] args) {

// TODO Auto-generated method stub

System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");  

WebDriver dr = new FirefoxDriver();

String url = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html";// "/Your/Path/to/main.html"

dr.get(url);

 

//点击第一个按钮,输出对话框上面的文字,然后叉掉

dr.findElement(By.id("alert")).click();

Alert alert = dr.switchTo().alert();

String text = alert.getText();

System.out.println(text);

alert.dismiss();

 

//点击第二个按钮,输出对话框上面的文字,然后点击确认

dr.findElement(By.id("confirm")).click();

Alert confirm = dr.switchTo().alert();

String text1 = confirm.getText();

System.out.println(text1);

confirm.accept();

 

//点击第三个按钮,输入你的名字,然后点击确认,最后

dr.findElement(By.id("prompt")).click();

Alert prompt = dr.switchTo().alert();

String text2 = prompt.getText();

System.out.println(text2);

prompt.sendKeys("jarvi");

prompt.accept();

 

}

 

}

 

 

小结:

 

从以上代码可以看出dr.switchTo().alert();这句可以得到alert\confirm\prompt对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有:

 

getText()    得到它的文本值

accept()      相当于点击它的"确认"

dismiss()     相当于点击"取消"或者叉掉对话框

sendKeys() 输入值,这个alert\confirm没有对话框就不能用了,不然会报错。

【下载】

webdriver允许我们设置默认的文件下载路径。也就是说文件会自动下载并且存在设置的那个目录中。

下面会给出firefox浏览器的具体设置方法。

代码

driver = Selenium::WebDriver.for :chrome, :profile => profile

# for firefox

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);

firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);

firefoxProfile.setPreference("browser.download.dir","c:\\downloads");

firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

WebDriver driver = new FirefoxDriver(firefoxProfile);

//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

driver.navigate().to(http://www.myfile.com/hey.csv);

 

 

【操作cookies

Web 测试中我们经常会接触到Cookies,一个Cookies主要属性有”所在域、name、value、有效日期和路径",下面来讲一下怎么操作Cookies

 

Java代码

public class CookiesStudy {

public static void main(String[] args) {

// TODO Auto-generated method stub

System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");  

WebDriver dr = new FirefoxDriver();

dr.get("http://www.51.com");

 

//增加一个name = "name",value="value"的cookie

Cookie cookie = new Cookie("name", "value");

dr.manage().addCookie(cookie);

 

//得到当前页面下所有的cookies,并且输出它们的所在域、name、value、有效日期和路径

Set<Cookie> cookies = dr.manage().getCookies();

System.out.println(String.format("Domain -> name -> value -> expiry -> path"));

for(Cookie c : cookies)

System.out.println(String.format("%s -> %s -> %s -> %s -> %s",

c.getDomain(), c.getName(), c.getValue(),c.getExpiry(),c.getPath()));

 

 

//删除cookie有三种方法

 

//第一种通过cookie的name

dr.manage().deleteCookieNamed("CookieName");

//第二种通过Cookie对象

dr.manage().deleteCookie(cookie);

//第三种全部删除

dr.manage().deleteAllCookies();

}

附加cookies:

获取cookie的值:

Set<Cookie> allCookies = driver.manage().getCookies();

for (Cookie loadedCookie : allCookies) {

   System.out.println(String.format("%s -> %s",loadedCookie.getName(), loadedCookie.getValue()));

}

根据某个cookie的name获取cookie的值:

driver.manage().getCookieNamed("mmsid");

删除cookie:

// You can delete cookies in 3 ways

// By name

driver.manage().deleteCookieNamed("CookieName");

// By Cookie

driver.manage().deleteCookie(loadedCookie);

// Or all of them

driver.manage().deleteAllCookies();

 

小结:

 

上面的代码首先在页面中增加了一个cookie,然后遍历页面的所有cookies,并输出他们的主要属性。最后就是三种删除cookie的方法。

 

【调用javascript

Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"+ value + "');})()");

 

 

打开一个alter框,然后这里driver被强制转换成JavaScriptExecutor:

public static void main(String[] agrs){

WebDriver driver=new FirefoxDriver();

((JavascriptExecutor)driver).executeScript("alter"(\"hello\")");

}

新手学python编码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

py编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值