当前位置:首页 > 自动化 > 正文

selenium自动化测试教程

一、golang从入门到精通,搭建本地selenium自动化测试环境使用Golang作为爬虫时,如果你的页面包含复杂的JS,普通的http.get或http.post如果不进行特殊处理,将无法解析页面源代码。
作为使用Python的一部分,您可以使用Selenium来爬取数据或使用Selenium来自动化测试。 那么我们如何用Golang来处理这个问题呢?
Golang实际上有Selenium。 作为测试Web应用程序的工具,Selenium可以模拟真实浏览器的行为,包括鼠标单击、滚轮和打字。
通过两堂课,我们将1.本地启动Selenium服务。 2.远程启动Selenium服务。

二、如何利用selenium来进行自动化页面测试

1.下载必要的依赖文件selenium-server-standalone-2.25.0.jar、junit-4.7.jar并将其放在项目的lib文件夹中(我这里使用的是Firefox浏览器作为客户端,所以有无需下载额外的浏览器执行器,如果您想使用IE或Chrome作为客户端,请下载相应的执行器

【2.创建测试项目,在文件中创建测试并添加。 以下代码:

importcom.thoughtworks.selenium.Selenium;

importjunit.framework.TestCase;

importorg.junit.

importorg.junit.Before;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.junit运行程序。 BlockJUnit4ClassRunner;

导入org.openqa.selenium.By;

导入org.openqa.selenium.WebDriver;

导入org.openqa.selenium.WebDriverBackedSelenium;;

导入org.openqa.selenium.support.ui.Wait;

导入org.openqa.selenium.support.ui.WebDriverWait;

 

importjava.io.IOException;

importstaticorg.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;

@RunWith(BlockJUnit4ClassRunner.class)

publicclasspickTestextendsTestCase{

protectedstaticSeleniumselenium;

privatestaticWebDriverdriver;

@Before

publicvoidcreateAndStartService()throwsIOException{

selenium=newWebDriverBackedSelenium(newFirefoxDriver(),"");

driver=((WrapsDriver)selenium).getWrappedDriver();

@After

publicvoidcreateAndStopService(){

飞行员。 quit();

<}

<

<@Test

<驱动程序。 get("http://www.google.com.hk");

WebElementsearchBox=driver.findElement(By.xpath("//*[@id=\"lst-ib\"]"));

SearchBox.sendKeys("selenium");

WebElementsearchButton=driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div[3]/center/input[1]"));

searchButton.click();

等待wait=newWebDriverWait(driver,30);

wait.until(visibilityOfElementLocated(By.xpath("//*[@id=\"ab_name\"]/span")));

}

}

3.运行这个测试,你会看到Firebox浏览器自动启动,然后自动输入selenum并搜索。

这样就进行了一个简单的自动化页面测试。 有些朋友可能不明白这段代码的含义。 在上面的代码中,我将部分标记为红色和蓝色。 让我简单解释一下。 Selenium通过包装浏览器来处理页面,因此我们首先创建一个链接到浏览器的WebDriver对象。 接下来,我们需要使用findeElement和XPath方法查找页面元素,以获取页面对象(代码的红色部分)。 因此,通常我们的一个点击操作会从服务器生成响应,这需要一段时间。 蓝色部分的代码是创建一个pending对象。 您可以使用XPath来确定返回后加载哪个页面元素。 该页面被视为已加载。 同时,等待的对象也有超时的情况。 参数,以便服务器永远不会返回错误。 我们仍然可以完成测试。 如何更快的确定页面元素的XPath,如下: