(一)定位元素、控制浏览器后退和前进

一、selenium自动化要做的事情

模拟鼠标和键盘来操作这些元素,操作包括点击、输入、右击、鼠标拖动等

二、定位元素

8种方法:org.openqa.selenium.By

...
<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
 
<input type="submit" id="su" value="百度一下" class="bg s_btn">
...

常用5种


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class baidu {

	public static void main(String[] args) {
		System.setProperty("webdriver.firefox.bin", "D:/Program Files (x86)/Mozilla Firefox/firefox.exe");
		System.setProperty("webdriver.gecko.driver", "E://selenium//geckodriver-v0.24.0-win64//geckodriver.exe");
		WebDriver driver=new FirefoxDriver();
		driver.get("http://www.baidu.com/");//向浏览器发送网址
		/*
		WebElement txtbox=driver.findElement(By.id("kw")); //根据属性id找到百度输入框
		CharSequence[] str={"selenium java"};
		txtbox.sendKeys(str);//文本框输入内容
		WebElement btn=driver.findElement(By.id("su")); //根据属性id=su找到百度一下搜索按钮
		btn.click();//点击
		*/
		
		WebElement txtbox=driver.findElement(By.name("wd")); 
		System.out.println(txtbox.getTagName());
		
		WebElement txtbox1=driver.findElement(By.tagName("input"));//因相同标签的tag很多,所以一般不使用
		System.out.println(txtbox1.getTagName());
		
		WebElement link=driver.findElement(By.linkText("新闻")); //link定位
		link.click();
		
		WebElement link2=driver.findElement(By.partialLinkText("百度首"));
		link2.click();
		
	}
}

Q1:id,name,class,xpath, css selector这些属性,你最偏爱哪一种,为什么?

A:css 、xpath 几乎所有的元素都可以定位到,但是它们的短处在于页面上更改了元素后位置很容易改变,所以首先使用的还是id或者name等。

 

三、控制浏览器后退、前进

 

浏览器提供了后退、前进按钮,方便的对浏览过的页面之间切换,那么WebDriver也提供了对应的back()、forward()方法模拟后退、前进按钮。

注意:用这种方法,每个页面的获取方式要用driver.get("xxxx") ,用driver.finsElement().click()是不起作用的。

就现象而言,用第一种方式,无论打开多少页面,都可返回。

用第二种方式,则如下图所示,并没有返回的箭头

所以,浏览器前进、后退,模拟的就是这个操作。

这种方式,有个缺点:只能是最新打开和之前的页面(两个页面)进行前进、后退,涉及多个页面,还需要其他方法

WebDriver.Navigation

public static void main(String[] args) {
		System.setProperty("webdriver.firefox.bin", "D:/Program Files (x86)/Mozilla Firefox/firefox.exe");
		System.setProperty("webdriver.gecko.driver", "E://selenium//geckodriver-v0.24.0-win64//geckodriver.exe");
		
		WebDriver driver=new FirefoxDriver();
		
		 driver.get("http://www.baidu.com/");//向浏览器发送网址
			
		 WebElement link=driver.findElement(By.linkText("新闻"));
			
			String newLink=link.getAttribute("href");
			System.out.println(newLink);
			
			//跳转页面
			driver.get(newLink);
			
			WebElement link2=driver.findElement(By.linkText("xxxxxx"));
			String newLink2=link2.getAttribute("href");
			driver.get(newLink2);
			System.out.println(newLink2);
			
			//跳回
			driver.navigate().back();
			System.out.println("往回跳");
			//往前跳
			//driver.navigate().forward();
			driver.navigate().to("http://www.google.com/");
			Thread.sleep(5000);
			driver.navigate().refresh();
		
	}

 

 

 

 

 

 

posted @ 2019-04-29 15:36  测试开发分享站  阅读(158)  评论(0编辑  收藏  举报