Java_Selenium

getText()    通常指的是<p>aaa</p>中的aaa 

对于<p text="aaa"></p>这种  就需要getAttribute("text")去获取

弹出对话框(Popup dialogs)
Alert alert = driver.switchTo().alert();
alert.accept();  //确定
alert.dismiss();  //取消
alert.getText(); //获取文本

表单(Form)
Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:
WebElement approve = driver.findElement(By.id("approve"));
approve.click();

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

上传文件
上传文件的元素操作:
WebElement adFileUpload =driver.findElement(By.id("WAP-upload"));
String filePath = "C:\test\\uploadfile\\media_ads\\test.jpg";
adFileUpload.sendKeys(filePath);

Windows 和 Frames之间的切换
driver.switchTo().defaultContent();     //返回到最顶层的frame/iframe
driver.switchTo().frame("leftFrame");    //切换到某个frame:
driver.switchTo().window("windowName"); //切换到某个window

调用Java Script
Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("JS脚本");

超时设置
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);//识别元素时的超时时间
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);//页面加载时的超时时间
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);  //异步脚本的超时时间

public class TestSelenium {
    WebDriver webDriver = null;
    @Before
    public void Setup(){
        File chromeDriverPath = new File("D:\\Selenium\\webdriver\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", chromeDriverPath.getAbsolutePath());
        webDriver = new ChromeDriver();
    }
 @Test
    public void testWait(){
        webDriver.get("http://www.baidu.com");
        WebElement webElement = webDriver.findElement(By.name("wd"));
        webElement.sendKeys("Selenium 2");
        webElement.submit();        
        //1. 显示等待
        (new WebDriverWait(webDriver, 10)).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                // TODO Auto-generated method stub
                return driver.getTitle().toLowerCase().startsWith("selenium");
            } 
        });
        System.out.println("Page title is:"+webDriver.getTitle());
        //1.1显示等待-2
       WebDriverWait wait = new WebDriverWait(driver,5);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("")));
        webDriver.navigate().back();
        //1.2显示等待-3
        WebDriverWait wait = new WebDriverWait(driver,//等待秒数//);
        wait.until(ExpectedConditions.visibilityOfElementLocated(//元素位置//));
        visibilityOfElementLocated,意思是只要被找的元素出现就停止等待。
        //2. 隐式等待
        webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        webDriver.findElement(By.xpath("//*[@id=\"u1\"]/a[1]")).click();
        webDriver.quit();
        可隐式等待的代码只写了一遍。虽然只是一遍,可每次执行driver.findElement()的时候          如果当时定位不到要找的元素都会执行一下这句
    }
}
 

显式等待可以自定义等待的条件,用于更加复杂的页面等待条件

(1)页面元素是否在页面上可用和可被单击:elementToBeClickable(By locator)

(2)页面元素处于被选中状态:elementToBeSelected(WebElement element)

(3)页面元素在页面中存在:presenceOfElementLocated(By locator)

(4)在页面元素中是否包含特定的文本:textToBePresentInElement(By locator)

(5)页面元素值:textToBePresentInElementValue(By locator, java.lang.String text)

(6)标题 (title):titleContains(java.lang.String title)

只有满足显式等待的条件满足,测试代码才会继续向后执行后续的测试逻辑

如果超过设定的最大显式等待时间阈值, 这测试程序会抛出异常。
————————————————
版权声明:本文为CSDN博主「天驱蚊香」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42123456/article/details/114474744

获取元素坐标
在“Console”中输入 'document.getElementById('元素ID').getBoundingClientRect()'后,回车
 

https://www.iteye.com/blog/m635674608-2173144
1. 利用 Selenium 自带的方法截图
getScreenshotAs() 函数可以返回 BASE64、BYTES 或 FILE 类型的数据 
public static void captureScreen(WebDriver driver,String screenName) throws IOException{          //判断是否存在screenpath目录 if(!(new File(screenpath).isDirectory())){ new         File(screenpath).mkdir(); } File screenShotFile =         ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);          FileUtils.copyFile(screenShotFile, new File(screenpath+screenName+".jpg"));
}
2.利用 Robot 类的 createScreenCapture() 方法
public static void captureScreen(String screenName, int x, int y, int width, int height) {
        try {
         BufferedImage capture = null; Rectangle area = new Rectangle(x, y, width, height);          Robot robot = new Robot(); capture = robot.createScreenCapture(area);
         String fn = screenpath + screenName + ".jpg";
         FileOutputStream out = new FileOutputStream(fn);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);                                  encoder.encode(capture);
        out.flush();
        out.close();
        } catch (Exception e) {
        e.printStackTrace();
        }
}
对于某些气泡悬浮框,如 title 属性值,需要将鼠标悬浮在元素上才可以显示出来。采用 Selenium 的 Actions 类去模拟鼠标操作,可以解决一些通过 javascript、css 控制的鼠标移动、悬浮操作 ,但是对于 title 这样的气泡悬浮框却无能为力,因为 Actions 方法只是模拟鼠标操作,而 title 属性值需要在真实的鼠标悬浮在元素上时才会显示出来。此时,可以先使用 Robot 类的 mouseMove() 方法将鼠标移到指定屏幕位置,再进行截图。
3. 在 Robot 类的 mouseMove() 方法中应用 Selenium 获取到的点坐标
Robot robot = newRobot();
Point point = element.getLocation();
robot.mouseMove(point.x+55, point.y+90);

mouseMove() 中的点坐标为 Selenium 获取到的元素的屏幕坐标,而通过 getLocation() 方法获得的元素坐标为元素相对于浏览器内的 document 对象的坐标,所以需要进行微调。

由于 Robot 类操作的是一些操作系统事件,所以在某些系统(如 X-Window 系统)中如果 Robot 类访问鼠标、键盘的操作需要特定权限,那么可能会抛出 AWTException。然而,在多平台上实现截图并不是我们在本文中需要考虑的内容。利用 Robot 类的截图方法可以截取指定区域的屏幕,相比第一种方法更加灵活,功能也更加强大。
 

对于页面中某些气泡悬浮框(如图 1 中的“到百度首页”字符串),如 title 和 alt 属性值,虽然使用 Robot 可以截取到,但是需要调节坐标位置。在我们实际应用中,由于我们一般都是通过 Remote Desktop Connection Manager 连接多台远程虚拟机,屏幕的大小有时会发生改变,因而元素的坐标位置也经常需要调节。

图 1. 气泡悬浮框示例

实现思路

所以对于此类情况,我们可以通过另外一种方式解决,即解析网页页面,取出 title 属性值,并根据 title 信息绘制成图片,最后将绘制好的图片添加到原来的图中并返回整张图片。从理论上讲,所有的页面元素,我们都可以通过此方法实现截图。实现方法如清单 4 所示。

清单 4. 抓取完整的屏幕截图

public static void captureFlyover(WebDriver driver,String xpath,String screenName) throws Exception{
    BufferedImage img;
    BufferedImage img1;
    //img1为抓取的不包含tooltip的屏幕截图
    img1 = gsscScreenshotImage(driver);
    //img为将悬浮框添加到img1后返回的屏幕截图
	img = gsscAddTooltip(driver.findElement(By.xpath(xpath)), img1);
	ImageIO.write(img, "png", new File(screenpath+screenName+".jpg"));
}

其中, gsscScreenshotImage() 方法调用的是第一种方式中的 getScreenshotAs() 方法。接着,我们来看一下 gsscAddTooltip() 的实现方式。我们首先在 gsscCreateTooltip() 创建了 tooltip 图像。根据传入的 Selenium 获取到的 element 对象,我们可以获取到元素的 title 和 font-family 等属性值以及元素的坐标位置。根据这些信息,我们创建出一个 img 图像。我们将图像的背景色设置为 #F5FCDE。但为了更加逼真,我们还可以通过 getCssValue() 方法获取到更多和元素有关的信息,如 background、border、padding 等等。

清单 5. 创建悬浮框

public static Point text_location;
	
//获取title属性值,创建tooltip
public static BufferedImage gsscCreateTooltip (WebElement element, int size) throws Exception{
	
	String text = element.getAttribute("title");
	String text_font = element.getCssValue("font-family");
	text_location = element.getLocation();
	int tooltip_h = size+7;
	
	BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
	Graphics2D tooltip = img.createGraphics();
        //设置悬浮框的宽度为文本的宽度加上7像素
	int tooltip_w = tooltip.getFontMetrics().stringWidth(text)+7;
	img = new BufferedImage(tooltip_w, tooltip_h, BufferedImage.TYPE_INT_ARGB);
	tooltip = img.createGraphics();
	//将创建图像的文字字体设置为从页面元素中获取到的文字字体
	tooltip.setFont(new Font(text_font, Font.PLAIN, size));
	tooltip.setPaint(Color.decode("#F5FCDE"));
	tooltip.fillRect(0, 0, tooltip_w, tooltip_h);
	tooltip.setPaint(Color.black);
	tooltip.draw3DRect(0, 0, tooltip_w-1, tooltip_h-1, true);
        //将文本绘制到图像上,drawString()并不支持文本的自动换行,当需打印的文                         
        //本太长时,需要自己实现自动换行
	tooltip.drawString(text,3,tooltip_h-5);
	tooltip.dispose();
	return img;
}


然后,我们在 gsscAddTooltip() 中进行判断,如果我们只想得到仅包含 tooltip 的图片,那么我们直接利用 tooltip 这个 BufferedImage 对象绘出图像并返回。否则将 tooltip 绘制在 img 中指定元素的坐标位置附近(以元素中心为坐标,向 x 和 y 方向分别偏移 20px)。

清单 6. 将悬浮框添加到 Selenium 截取的图片中

public static BufferedImage gsscAddTooltip (WebElement element, BufferedImage img) throws Exception{	
	// 创建tooltip
	BufferedImage tooltip = gsscCreateTooltip(element, 12);
	int tooltip_w = tooltip.getWidth();
	int tooltip_h = tooltip.getHeight();
	BufferedImage buffImg;
	Graphics2D graphic;
	
	if (img != null){
		// 将tooltip添加到img中
		int img_w = img.getWidth();
		int img_h = img.getHeight();
		
		if (img_w >= (tooltip_w+text_location.getX())){
			buffImg = new BufferedImage(img_w, img_h+tooltip_h+2, BufferedImage.TYPE_INT_ARGB);
		}else{
		buffImg = new BufferedImage(tooltip_w+text_location.getX()+10, img_h+tooltip_h+2, BufferedImage.TYPE_INT_ARGB);
		}
		graphic = buffImg.createGraphics();
		graphic.drawImage(img, 0, 0, null);
		graphic.drawImage(tooltip, text_location.x+20, text_location.y+20, null);
	}else{
		buffImg = new BufferedImage(tooltip_w+3, tooltip_h+2, BufferedImage.TYPE_INT_ARGB);
		graphic = buffImg.createGraphics();
		graphic.drawImage(tooltip, 3, 1, null);
	}
	graphic.dispose();
	return buffImg;
}

图 2. 利用第三种方式截到的图(仅显示部分)

需要注意的问题

利 用该方法截取百度页面(http://www.baidu.com/s?wd=mytest&rsv_bp=0&ch=& tn=baidu&bar=&rsv_spt=3&ie=utf-8&rsv_sug3=1& inputT=7063)中的百度 logo 的 title“到百度首页”这个字符串的时候,截到的却是乱码。利用 FireBug 查看该网页的源代码才发现,原来该元素的字体被设置成了 arial。当页面文字被设置成某些西方字体如 arial 这样的字体时,调用 drawString() 方法打印中文字符会出现乱码。这时,只要将字体改为某些支持的字体就可以了,如:tooltip.setFont(newFont("宋体", Font.PLAIN, size));

图 3. 百度搜索结果页面的字体

图 4. 修改字体前后截图对比(仅显示部分)

对动态生成图片方法的改进

在 captureFlyover() 函数中,页面指定元素是通过 xpath 来获取的,该实例只返回了一个页面元素。如有需要,可以根据 xpath 表达式获取到所有符合条件的页面元素,然后将这些页面元素逐一添加到截图中,从而实现在同一个页面中获取到多个悬浮框的效果。但这种方法面临的另一个问题就是,多个悬浮框有可能会重叠,需要注意每个悬浮框在截图中显示的具体位置。

清单 7. 利用 xpath 获取多个页面元素

 //driver.findElements(By.xpath(xpath)会返回符合xpath表达式的所有元素,而 
 //driver.findElement(By.xpath(xpath)会返回符合xpath表达式的第一个元素
 img = gsscAddTooltips(driver.findElements(By.xpath(xpath)), img1);

通过解析网页动态生成图片,需要编写比较多的代码,实现难度相对比较大,一般只有在需要大量的截取某同类型的图片且无法通过 getScreenshotAs() 方法实现时才会选择。

结束语

本文通过示例代码,介绍了在用 Selenium 进行自动化测试时可以选用的三种网页截图方法。三种方法,各有优劣,可以适用在不同场景。读者也可以利用 JNI,通过调用第三方组件的方式来实现网页截图。但由于我们对性能并没有太高的要求,所以在实际应用中并未采用这种做法,这里也不再多述。

http://www.ithov.com/linux/131668_2.shtml

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值