selenium开发-C#/java/Python

背景:之前由于自己有编写CefSharp.WinForms 窗体版以及 接口化 WCF+CefSharp.WinForms的网站版本,但是由于某些原因,延伸出Selenium学习与研究

总结:selenium特点是在做自动化测试,如果公司需要自动化测试是个不错的选择,开发语言包含很多。你完全可以使用自己熟悉的语言进行开发,请查看 https://docs.seleniumhq.org/docs/ 通过几天的摸索,个人比较还是建议大家最后部署在windows平台,linux平台由于缺少可视化,在调试的时候会有很多坑。

1.C#调用selenium

   请参照 http://www.mamicode.com/info-detail-2746933.html

  1、我们新建一个C#控制台程序

  2、使用Nuget搜索以下依赖库

  需要引用的核心库是Selenium.RC,Selenium.Support,Selenium.WebDriver

     MvcWeb版也可以运行,挂在IIS可以很好运行

using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;




namespace Maxiot.ResourceServer.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/

        public ActionResult Index()
        {
            return View();
        }



        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="accesstoken"></param>
        /// <param name="value">非空参数必须传入数据</param>
        /// <returns></returns>
        public JsonResult GetData()
        {
            try
            {
                using (IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver())
                {
                    driver.Navigate().GoToUrl("www.baidu.com");
                    var timeouts = driver.Manage().Timeouts();
                    Thread.Sleep(3000);
                    var source = "aaa" + driver.PageSource;
                    return Json(source, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {

                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
View Code

2.Java调用selenium

  使用Maven导入包

<!-- selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<!-- <version>3.4.0</version>-->
</dependency>
package com.example.demoselenium.controller;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.awt.event.KeyEvent;
import java.rmi.ServerException;
import java.security.Key;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/common/")
public class CommonController {


    @RequestMapping(value = "selenium/OpenChrome", consumes = "application/json", method = RequestMethod.GET)
    public String getOpenChrome() throws ServerException {
        String restResult = "aaaa";
        try {
            //设置属性,通过https://sites.google.com/a/chromium.org/chromedriver/下载对应驱动,如果是linux部署需要下载linux对应驱动
            //System.setProperty("webdriver.chrome.driver", "chromedriver");    //linux设置,
            //System.setProperty("webdriver.chrome.driver", "D:\Program Files (x86)\chromedriver_win32\chromedriver.exe");
            ChromeOptions a = new ChromeOptions();
            a.addArguments("--no-sandbox");
            a.addArguments("--disable-dev-shm-usage");
            //a.addArguments("window-size=1920x3000"); //指定浏览器分辨率
            a.addArguments("--disable-gpu"); //谷歌文档提到需要加上这个属性来规避bug
            //a.addArguments("--hide-scrollbars"); //隐藏滚动条, 应对一些特殊页面
            //a.addArguments("blink-settings=imagesEnabled=false"); //不加载图片, 提升速度
            a.addArguments("--headless"); //浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
            WebDriver driver = new ChromeDriver(a);
            driver.get("http://dpmysql1:802/#/login");
            //如果网页加载不出来的话,get需要加载的时候会至少5秒
            String title = driver.getTitle();
            restResult += "title:" + title;
            //加载不成功,title的就是Ip,可以通过延时时间+title判断是否加载成功
            String dataSoruce = driver.getPageSource();
            restResult += "dataSource:" + dataSoruce;
            Thread.sleep(5000); //等待跳转加载
            WebElement account = driver.findElement(By.id("account"));
            if (account != null) {
                account.sendKeys("datamanager");//输入账号
                String strAccount = account.getAttribute("value");
                restResult += "account:" + strAccount;
            }
            WebElement password = driver.findElement(By.id("password"));
            if (password != null) {
                password.sendKeys("123");//输入账号
                String strPassword = password.getAttribute("value");
                restResult += "password:" + strPassword;
            }
            WebElement btn = driver.findElement(By.xpath("//*[@id='app']/form/div/div[6]/div/button"));
            if (btn != null) {
                btn.click(); //登录
                restResult += "btn:点击登入系统";
            }

            Thread.sleep(10000); //等待跳转加载
            dataSoruce = driver.getPageSource();
            String url = driver.getCurrentUrl(); //获取登录后的新窗口的url
            if (url.equals("http://dpmysql1:802/#/newhome")) {

                //登录成功
                //driver.findElement(By.xpath("//*[@id='app']/div/section/section/div[3]/div[1]/span")).click(); //点击按钮
                //driver.findElement(By.xpath("//*[@id="app"]/div/section/section/div[3]/div[2]/ul[1]/li[2]/a")).click(); //点击按钮
                //driver.findElement(By.xpath("//*[@id="app"]/div/div/section/div[1]/div/div/div[2]/div/div[2]/div/div[1]/div/div[4]/div[2]/table/tbody/tr[6]/td[10]/div/i[1]")).click(); //点击按钮
                restResult += "成功";

            } else {
                //失败
                //String message = driver.findElement(By.xpath("//*[@id="app"]/form/div/div[5]/div[2]/p")).getText();
                //System.out.println("*******" + message);
                restResult += "失败" + url + "--" + dataSoruce + "失败";
            }
            //加载不成功,title的就是Ip,可以通过延时时间+title判断是否加载成功
            System.out.printf(title);
            System.out.println("*******");
            driver.close();

            return restResult;
        } catch (Exception e) {

            return restResult + "错误" + e.getMessage();
        }

    }


    /**
     *
     * @param driver 浏览器驱动
     * @param xpath xpath定位表达式
     */
    public static void javaScriptClick(WebDriver driver, String xpath) {
        WebElement element = driver.findElement(By.xpath(xpath));
        try{
            if(element.isEnabled() && element.isDisplayed()){
                System.out.println("使用JS进行也面元素单击");
                //执行JS语句arguments[0].click();
                ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
            }else {
                System.out.println("页面上元素无法进行单击操作");
            }
        }catch (StaleElementReferenceException e){
            System.out.println("页面元素没有附加在页面中" + Arrays.toString(e.getStackTrace()));
        }catch (NoSuchElementException e){
            System.out.println("在页面中没有找到要操作的元素" + Arrays.toString(e.getStackTrace()));
        }catch (Exception e){
            System.out.println("无法完成单击操作" + Arrays.toString(e.getStackTrace()));
        }
    }

}
View Code

Linux运行selenium

1.需要在Linux上面安装Chrome 参考 https://www.cnblogs.com/z-x-y/p/9506941.html

1、安装chrome

用下面的命令安装最新的 Google Chrome

yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
也可以下载到本地再安装
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install ./google-chrome-stable_current_x86_64.rpm
安装必要的库
yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts

2、安装 chromedriver

chrome官网 wget https://chromedriver.storage.googleapis.com/2.38/chromedriver_linux64.zip
淘宝源(推荐)
wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zip

  将下载的文件解压,放在如下位置

  unzip chromedriver_linux64.zip

/usr/bin/chromedriver

  给予执行权限

chmod +x /usr/bin/chromedriver

目前Java编写的测试脚本在linux上面运行还是有些问题,比如登录按钮事件在windows上面可以触发,Linux失败,暂时我打算在去研究下Python

java代码下载:https://pan.baidu.com/s/1lnJXK__A8ZcIl3oVJyFC9w

Python 编写 selenuim 

      安装相应的环境:  可到官网下载最新版本 Python

       工具:    我选择Pycharm

          配置环境path环境变量,为了方便命令执行,请配置

     

         cmd查看python版本,如果命令无效,就可能是安装或环境变量未配置成功

         

  安装selenium

  

  查看安装的selenium

         

        如果实在cmd配置不好就使用cmd命令行 cd 进入python安装目录下的script文件夹下,使用pip install selenium

   

        我的PyCharm不能识别pip install selenium 安装的 selenium 我选择在PyCharm进行安装  

         

        代码阶段

         

import selenium.webdriver
from time import  sleep


#实例化对象
driver=selenium.webdriver.Chrome()
try:
    #设置链接
    driver.get("http://10.60.136.145:802/#/login")
    sleep(3)    #间隔3秒钟
    title = driver.title    #获取网页标题
    dataSoruce = driver.page_source #获取网页资源
    account = driver.find_element_by_id("account")  #获取账号
    if not account is None:
        account.send_keys("datamanager")    #设置账号

    password = driver.find_element_by_id("password")
    if not password is None:
        password.send_keys("123")

    btn=driver.find_element_by_xpath("//*[@id='app']/form/div/div[6]/div/button")
    if not btn is None:
        btn.click()
except:
    print("出错")
finally:
    driver.close()
View Code

       代码执行后会自动运行谷歌浏览器,并打开设置的网址,然后进行账号和密码登录

原文地址:https://www.cnblogs.com/shexunyu/p/11398944.html