Selenium 更强的查找元素的方法

package demo.skillport;

import java.io.File;
import java.util.List;

import junit.framework.Assert;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.android.AndroidDriver;

public class Test{
	private static final double CAPTURE_TIME_WAIT = 10;
	private static final boolean FOUND = true;
	private static final boolean NOT_FOUND = false;
	private AndroidDriver driver;
	private String captureDir = "C:\\";
	
	public Test(){
		driver = new AndroidDriver();
	}
	public Test(AndroidDriver driver){
		this.driver = driver;
	}
	/*这个方法中,使用By(通常使用By.xpath)来获取元素,同时给一个name来帮助查找/定位元素,
	至于如何获取该元素中的name,则由type来选择
	*/
	public WebElement getElementWithName(By by, String name, String type) {
		// 获取元素列表
		List<WebElement> wel = driver.findElements(by);
		String method="";
		if(type.equals("tagName")){
			method = "getTagName()";
		}
		else if(type.equals("text")){
			method = "getText()";
		}
		for (WebElement w : wel) {
			String eText="";
			// 通过遍历元素及对应的方法获得eText内容
			if(null != w){
				if(type.equals("tagName")){
					eText = w.getTagName();
				}
				else if(type.equals("text")){
					eText = w.getText();
				}
					
			}
			// 对内容和给出的name进行比对,只要eText中包含name并满足其他条件,则返回该元素
			if (!eText.isEmpty() && -1 != eText.indexOf(name) && w.isEnabled()) 
			{
				logElementCheck(name, FOUND);
				return w;
			}
		}
		logElementCheck(name, NOT_FOUND);
		String timeStamp = String.valueOf(System.currentTimeMillis());
		captureScreen(captureDir, 
				String.format("%s_%s.png", timeStamp, name),
				String.format("(%s.%s == %s) is not found", by.toString(), method, name));
		return null;
	}

	private void captureScreen(String dirName, String photoName, String errMsg){
        try {
            sleep(CAPTURE_TIME_WAIT);
            File scrFile = driver.getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File(dirName + "//" + photoName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        logErr(String.format("%s. Snapshot is: %s", errMsg, photoName));
        Assert.assertNotNull(null);
    }

	private static void sleep(double seconds) {
		try {
			Thread.sleep((long) (seconds * 1000));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void logElementCheck(Object element, boolean isFound) {
		if(isFound)
			System.out.println(String.format("---><] %s is found.", element.toString()));
		else
			System.out.println(String.format("---><] %s is not found.", element.toString()));
	}
	
	private static void logErr(Object str) {
		System.err.println("err ] " + str.toString());
	}
	

	
}


发布了26 篇原创文章 · 获赞 3 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章