利用selenium技术自动测试网上购物及环境搭建(附yuan代码)

具体内容利用java+selenuium,对京东网站进行购物,包括流程:用户登入、查找商品、选定测评、加入购物车、下单,如下两图:

 

环境搭建:

1. 下载eclipse安装包并安装

2.下载基于java的selenium包:本次配置下载的包为:selenium-java-3.141.59.zip

下载地址:http://docs.seleniumhq.org/download/

3. eclipse中导入selenium包内的所有jar包:client-combined-3.141.59、client-combined-3.141.59-sources、以及lib下的所有包

具体步骤:

a.先创建一个项目-->右击-Build Path-Add library-->user library-点击User libraries

b.进入User libraries后,新建一个selenium的存储jar包,New-命名为selenium-->点击selenium-Add Externerl JARs..将selenium-java-3.141.59.zip解压后的所有jar包添加进来。

4. 利用chrome浏览器时,需要先下载chromedriver:

注意先查看安装的chrome浏览器版本,然后再下载对应的chromedriver

例如本地浏览器通过菜单栏-->帮助-->关于Google Chrome可以看到本地chrome版本 76.0.3809.132(正式版本)(32 位)

通过查阅 chromedriver与chrome版本映射表,得知需要下载chromedriver版本;

chromedriver下载地址:http://chromedriver.storage.googleapis.com/index.html

这里最好将chromedriver(chromedriver.exe)放在与chrome浏览器(chrome.exe)同一目录下这里放在:C:\Program Files\Google\Chrome\Application下了;并且将chromedriver的路径添加到系统环境变量Path下:环境变量配置在,计算机->属性->高级系统设置->环境变量内进行配置

代码:

package taobao;

public class PurchaseInJD1 {
    public static void main(String []args){
        //加载驱动
    	System.setProperty("webdriver.chrome.driver", 
				"C:\\Users\\ASUS\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\chromedriver_win32\\chromedriver.exe");
		  SeleniumChromeDriverJD1 scd = new SeleniumChromeDriverJD1();
        //开始
        scd.connect();
        //跳转链接到到京东页面
        scd.goUrl("https://www.jd.com/");
        //点击“登录”
        scd.clickLinkText("登录");
        //点击“账户登录”
        scd.clickLinkText("账户登录");
        //输入用户名和秘密、点击登入
        scd.loginToJD();

        //增加时间拖动滑块进行验证
        scd.delay(5);
        scd.chazhao();
        scd.clickXPath("//*[@id=\"search\"]/div/div[2]/button/i");
        
      //提交订单
      //scd.clickXPath("//button[@id='order-submit']");

        //切换到新打开的窗口
        scd.switchToWindowTitle("鲜花 - 商品搜索 - 京东");

        //选择品牌中的 插画
        System.out.print("1");
        scd.clickXPath("//*[@id=\"brand-437357\"]/a");
        //选择送礼对象中的 情侣
      
        scd.delay(2);
        scd.clickXPath("//*[@id=\"J_selector\"]/div[1]/div/div[2]/div[1]/ul/li[2]/a");
        
        //具体一种
        System.out.print("2");
        scd.clickXPath("//*[@id=\"J_goodsList\"]/ul/li[1]/div/div[4]/a/em");

        //切换到最后打开的窗口,即商品详情页
        scd.goLastPage();	
        
        //点击数量加一//*[@id="choose-btns"]/div/div/a[2]
        scd.clickXPath("//*[@id=\"choose-btns\"]/div/div/a[2]");
        //点击加入购物车
        
        scd.clickLinkText("加入购物车");
        
        //去购物车中结算
        scd.clickXPath("//a[@id='GotoShoppingCart']");
        
        //去结算
        scd.clickXPath("//a[contains(string(), '去结算')]");
   
        
        //关闭驱动
       // scd.disconnect();
    }
}
package taobao;

import java.util.ArrayList;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumChromeDriverJD1 {
    private static WebDriver chromeDriver;
    private static WebDriverWait wait10Secs; //允许网站响应的时间

    public SeleniumChromeDriverJD1()
    {
        chromeDriver = null;
        wait10Secs=null;
    }

    //开始测试
    public void connect()
    {
        ChromeOptions chromeOptions= new ChromeOptions();
        chromeOptions.addArguments("--start-maximized"); //使得网页最大化
        chromeDriver = new ChromeDriver(chromeOptions);
        wait10Secs = new WebDriverWait(chromeDriver,10);//允许网站在10秒内响应
    }

    //关闭测试
    public void disconnect()
    {
        // close the test window
        chromeDriver.close();
        chromeDriver.quit();
    }

    /**跳转到某网页,或者打开某个主页。
     * @param strURL URL形式的网址,主页,网页
     */
    public void goUrl(String strURL)
    {
        chromeDriver.get(strURL);
    }

    /**
     * @return 当前打开窗口的最后一个句柄
     */
    private String getLastHandle()
    {
        //获取当前打开窗口的所有句柄
        Set<String> allhandles = chromeDriver.getWindowHandles();
        ArrayList<String> lst = new ArrayList<String>(allhandles);
        return lst.get(lst.size()-1);
    }

    /**进入打开窗口的最后一个。
     *
     */
    public void goLastPage()
    {
        String lastHandle = getLastHandle();
        chromeDriver.switchTo().window(lastHandle);
    }

    /** 依据网页的字符串信息,来点击。
     * @param strLinkText  字符串,网页上可点击的元素。
     */
    public void clickLinkText(String strLinkText)
    {
        By orgnLocation = By.linkText(strLinkText);
        // WebDriver的时间,10秒钟内,等待“登录”链接出现。
        wait10Secs.until(ExpectedConditions.visibilityOfElementLocated(orgnLocation));
        //链接出现后,点击它。
        WebElement elemOrgn = chromeDriver.findElement(orgnLocation);
        elemOrgn.click();
        delay(1);
    }

    //登录
    public void loginToJD()
    {
        By userLocation = By.xpath("//*[@id=\"loginname\"]");
        chromeDriver.findElement(userLocation).sendKeys("152#####851");
        delay(1);
        //
        By passwordLocation = By.xpath("//input[@id='nloginpwd']");
        chromeDriver.findElement(passwordLocation).sendKeys("#####");
        delay(1);
        By loginLocation = By.xpath("//a[@id='loginsubmit']");
        chromeDriver.findElement(loginLocation).click();
    }
    
    //查找
    public void chazhao() {*[@id="key"]
    	 By need = By.xpath("//*[@id=\"key\"]");
         chromeDriver.findElement(need).sendKeys("鲜花");
    }
    
    
    /** 依据XPath路径信息,来点击。
     * @param strXPath  字符串,XML的XPath查询。
     */
    public void clickXPath(String strXPath)
    {
        By orgnLocation = By.xpath(strXPath);
        // WebDriver的时间,10秒钟内,等待strXPath链接出现。
        wait10Secs.until(ExpectedConditions.visibilityOfElementLocated(orgnLocation));
        //strXPath链接出现后,点击它。
        WebElement elemOrgn = chromeDriver.findElement(orgnLocation);
        elemOrgn.click();
        delay(1);
    }

    //切换到title=strTitle的窗口
    public String switchToWindowTitle(String strTitle)
    {
        String curHandle = null;//记录包含strTitle的窗口句柄。
        for(String winHandle : chromeDriver.getWindowHandles())
        {
            chromeDriver.switchTo().window(winHandle);
            if (chromeDriver.getTitle().contains(strTitle))
            {
                curHandle = winHandle;
                break;
            } //end of if...
        } //end of for...
        return curHandle;
    }

    //延时
    public void delay(int seconds){
        try {
            Thread.currentThread().sleep(seconds * 1000);//毫秒
        } catch(Exception e){ }
    }

}

注意事项:

1.SeleniumChromeDriverJD1类里面的loginToJO函数中填写自己京东的电话和密码;

2.测试加入购物车后记得额外取消购物

3.如果登录过程在存在滑动验证,自行手动划过;

4.淘宝等其他购物网站可参考仿照写,Xpath不会写的推荐去看  XPath 教程 (w3school.com.cn)

5.chromediver的位置要修改为自己电脑上的位置

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值