`
zhangfy068
  • 浏览: 143763 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

selenium学习笔记

 
阅读更多

1 、webdriver 与 selenium RC

 

 

2、css选择器

By.cssSelector("#f_modify_box > div.hd > a.cls") 实际如下



 3、xpath选择器

id为userBtn 下的 a下的img 

selenium.isElementPresent("id('userBtn')/x:a/x:img"))

By.xpath("//li[@id='userBtn']/a/img")


 

4、点击链接,使用driver.getTitle()来验证

 

6、IE下出现了ElementNotFoundException ,但FF运行正常

网上查了半天,都说是IE的保护模式,但是貌似只有vista系统,在IE选项->安全里才有那个选项。

重装IE7,问题得到解决。

 

7、火狐出现什么问题呢?

driver.get(www.google.com)

不能通过,要加上http://www.google.com才能够正常运行

 

8、webdriver 如何处理ajax

 

案例:我评论了一条信息,但是页面上显示的是ajax处理的,我要判断页面上是否新增了这条评论。直接判断确拉错了信息(因为AJAX反应没那么快)。

所以采用以下写法,5秒之内判断是否能够成功返回正确值,如果可以择判断运行正确。

 

 

 

	boolean result=new WebDriverWait(driver, 5).until (new ExpectedCondition<Boolean>() {  
			   public Boolean apply(WebDriver driver) {  
			    boolean   result = false;  
			       try {  
			    		List elements=driver.findElements(By.xpath("id('content_li')/li/p"));
			    		if(elements.size()<0)Assert.fail("评论失败,没有增加评论");
			    		WebElement ele=(WebElement) elements.get(0);
			    		System.out.println("text:"+ele.getText());
			    		return ele.getText().contains(s);
			       } catch(Exception e){     
			         System.out.println("error");
			       }
				return result;  
			   }  
			});  
		if(result){
			Assert.assertTrue(true);
		}else Assert.assertTrue(false);

 

 

Wait<WebDriver> wait = new WebDriverWait(driver, 30);
WebElement element= wait.until(visibilityOfElementLocated(By.id("some_id")));

Where “visibilityOfElementLocated” is implemented as:

public ExpectedCondition<WebElement> visibilityOfElementLocated(final By locator) {
  return new ExpectedCondition<WebElement>() {
    public WebElement apply(WebDriver driver) {
      WebElement toReturn = driver.findElement(locator);
      if (toReturn.isDisplayed()) {
        return toReturn;
      }
      return null;
    }
  };
}

9、该element is not visible

在页面上肉眼确实TEXTAREA可见,但是运行click函数的时候,抛出异常。

于是写了一个循环 一直判断是否可见,,,经观察,是由于此控件加载未完成。

于是等待此控件加载完成才,click。

 

 WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(" "))); 

 

 while(true){
	    	if(ele.isDisplayed())break;
	    }
    for(int second=1;;second++){
			    	if(second>60)Assert.fail("超时了");
			    	if(text.equals("")){
			    		 mouseMenu.click(ele);
						   mouseMenu.perform();
						   Thread.sleep(1000);
						   System.out.println(n);
						   if(i==3){
							   text=driver.findElement(By.xpath("id('ui-dlg-linkShare')/div[1]/h2")).getText();
						   }else{
							   text=driver.findElement(By.xpath("id('ui-dlg-emailShare')/div[1]/h2")).getText();
						   }
						   n++;
			    	}else{
			    		break;
			    	}
			    }

 

10、IE自动保存表单,FF不能,要读取profile

IE-选项-内容-》保存表单

 

11、有关xpath取值不正确

用FF插件弄的是

 By.xpath("/html/body/div[3]/div[3]/div/a"));
 用GOOGLE插件xpathOnClick 这个就能找到element

 

By.xpath("/html/body/div[contains(concat(' ', @class, ' '), ' wrap ')]/div[3]/div[contains(concat(' ', @class, ' '), ' dt_sidbox ')]/a"));

 12、一个神奇的问题

之前用JUNIT做测试,引用了他的包,后来改成了testng,

在做suite的时候,发现运行不了。

解决结果:删除junit包。

使用ant  build.xml生成的报告也产生了影响。

 

13、chrome最大化

 

 DesiredCapabilities capabilities = DesiredCapabilities.chrome();

  capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));

  WebDriver driver = new ChromeDriver(capabilities);

14、增加FF插件

File file =newFile(".\\res\\firebug-1.9.1-fx.xpi");
FirefoxProfile firefoxProfile =newFirefoxProfile();
try{
firefoxProfile.addExtension(file);
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
firefoxProfile.setPreference("extensions.firebug.currentVersion","1.9.1");

 

15、webdriver代替TextIsPresent的方法  

public boolean isContentAppeared(WebDriver driver,String content) {  boolean status = false;  try {  
        driver.findElement(By.xpath("//*[contains(.,'" + content + "')]"));  
        System.out.println(content + " is appeard!");  
        status = true;  
    } catch (NoSuchElementException e) {  
        status = false;  
        System.out.println("'" + content + "' doesn't exist!"));  
    }  
    return status;  
}  

 16、自定义table

 

public class Table {  
    private String locator;  
    private WebDriver driver;  
      
    public Table(WebDriver d, String locator) {  
        this.driver = d;  
        this.locator = locator;  
    }  
  
    public String getCellText(int row, int col){  
          
        String xpath = locator + "//tr[" + row  +"]/td[" + col + "]";  
        WebElement cell = driver.findElement(By.xpath(xpath));  
        return cell.getText();        
    }     
  
}  

 17、webdriver常用操作http://blog.csdn.net/xiecj_2006/article/details/7869033

18、截图

 

package test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class Test_ShotScreen {
public static void main(String[] args) throws IOException, InterruptedException{
 
String url = "http://www.51.com";
//打开chrome
   WebDriver dr = new InternetExplorerDriver();
        dr.get(url);
        
        
        //这里等待页面加载完成
        Thread.sleep(5000);
        //下面代码是得到截图并保存在D盘下
        File screenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
        //FileUtils.copyFile(screenShotFile, new File("D:/test.png"));  
        FileUtils.copyFile(screenShotFile, new File("D:\\AutoScreenCapture\\" + getCurrentDateTime()+ ".jpg"));  
        
        dr.quit();
}
 
public static String getCurrentDateTime(){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");//设置日期格式
//System.out.println(df.format(new Date()));
return df.format(new Date());
}
}

  19、webdriver与selenium切换

 

// You may use any WebDriver implementation. Firefox is used here as an example
WebDriver driver = new FirefoxDriver();

// A "base url", used by selenium to resolve relative URLs
 String baseUrl = "http://www.google.com";

// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

// Perform actions with selenium

selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");

// Get the underlying WebDriver implementation back. This will refer to the
// same WebDriver instance as the "driver" variable above.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();

//Finally, close the browser. Call stop on the WebDriverBackedSelenium instance
//instead of calling driver.quit(). Otherwise, the JVM will continue running after
//the browser has been closed.
selenium.stop();

  20、webdriver支持sari

 

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("safari");
CommandExecutor executor = new SeleneseCommandExecutor(new URL("http://localhost:4444/"), new URL("http://www.google.com/"), capabilities);
WebDriver driver = new RemoteWebDriver(executor, capabilities);

 

21、suite之间不应该存在依赖,虽然代码static存在依赖,但是浏览器之间不是同一个driver了。。

 

22、如何上传文件

 

Yup the Selenium devs thought about this ages ago. You can just use driver.findElement(By.id(“foo”)).sendKeys(“AbsoluteFileLocation”); If the element you are sending text to is and  it will upload the file.

23、如何下载
 
24、校验图片
driver.get("https://demo.mynexia.com/login"); 
    WebElement ele = driver.findElement(By.cssSelector("#content_footer .left")); 
    String actual = ele.getCssValue("background-image"); 
    String expected = "/assets/schlage_footer_logo.gif"; 
    assertTrue(actual.contains(expected));
 

5、鼠标滑过

有时候遇到了ElementsNotVisible是因为要鼠标滑过触发JS,所以只要执行鼠标动作,再点击就OK了

 

 //Perform mouse over action
    Actions mouseMenu = new Actions(driver);
    mouseMenu.moveToElement(menu).build().perform();
System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");  
//		driver = new FirefoxDriver();
服务器运行java -jar selenium-server-standalone-2.25.0.jar -role hub
节点注册java -jar selenium-server-standalone-2.25.0.jar -role webdriver -hub http://localhost:4444/grid/register -port 6666

 

 

在一般情况下,java -jar selenium-server-standalone-.jar就够用了。但是有些选项,还是蛮有用的,可以关注一下。

-port: 指定Selenium Server的侦听的端口号。如果没有指定port,使用4444。

-profilesLocation: (仅Firefox)指定Firefox的profile文件位置。什么?不晓得Firefox的profile是干啥用?简单的说,就是将你浏览网站的cookie、历史记录等记录到一个文件夹下面(点击这里查看详细)。 为什么需要这个呢?在默认情况下,Selenium Server会使用一个空的profile文件夹的,也就是它启动的Firefox是一个“干净 ”的浏览器。有时候,这并不是你所想要的,例如,在某些网站,做过的一些设置(如关掉页面上恼人的浮层),如果是“干净”的浏览器,那你的设置就没法生效 的。

-browserSessionReuse:可以节省tests运行时间的。在每个test运行的时候,不用重新再次启动Firefox,复用旧的Firefox。

-userExtensions :firefox的用户扩展。将一段js代码load到selenium里面去,非常有用。对于一些已经实现了使用JS来验证的工具,无缝的集成到 Selenium里面,这意味着原本单个页面的手工执行JS工具,可以通过Selenium自动化来执行这些工具。

更多的选项,可以来查看帮助:

java -jar /selenium-server-standalone-.jar –help
 
 

2.1 IE
Internet Explorer不支持类似于Firefox的profile,它是基于Windows用户的,想使用一个新的profile,只有创建一个新的Windows用户。

2.2 Firefox
如果是启动Selenium Server,那很简单,help命令中就有,可以使用选项-firefoxProfileTemplate或者选项-profilesLocation。

java -jar selenium-server-standalone-2.22.0.jar –firefoxProfileTemplate d:\seelenium\firefox_profile\

如果是启动Selenium Grid,Google了一下,没有找到办法。但是在查看Selenium源代码的时候,发现已经支持了,尝试之,果然有效。

java -jar selenium-server-standalone-2.22.0.jar -Dwebdriver.firefox.profile=myProfile -port 4001 -role node -hub http://127.0.0.1:4000/grid/register 

 
2.3 Chrome
Chrome使用profile,在官方版本中,目前没法在Selenium Server或者Selenium Grid端指定的。但是它可以在客户端指定(有些奇怪哈)。

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--user-data-dir=/path/to/profile/directory"));
    WebDriver driver = new ChromeDriver(capabilities);

详细的请参考:
http://code.google.com/p/selenium/wiki/ChromeDriver

此外,Chrome使用profile的时候,对于同一个profile,当前只能够启动一个Chrome浏览器实例,请见:
http://code.google.com/p/chromedriver/issues/detail?id=79

webdriver高级用法

http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-and-implicit-waits

 

 

xpath 

For example, if your dynamic ids have the format <input id="text-12345" /> where 12345 is a dynamic number you could use the following XPath: //input[starts-with(@id, 'text-')]

 

To demonstrate, the element <span class="top heading bold">can be located based on the ‘heading’ class without having to couple it with the ‘top’ and ‘bold’ classes using the following XPath: //span[contains(@class, 'heading')]. Incidentally, this would be much neater (and probably faster) using the CSS locator strategy css=span.heading

 

  • XPath: //div[contains(@class, 'article-heading')]
  • CSS: css=div.article-heading
  • 综上CSS instead  xpath 更快

 

11、使用HtmlUnitDriver 找不到元素

解决办法(HtmlUnitDriver)driver.setJavaScript(true);不同网站,不一定需要设置这个。。。比如eoeandroid设置这个参数就会报错。返回JQUERY的错误。

  • 大小: 13.2 KB
  • 大小: 13.1 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics