背景:以前因为本身有编写CefSharp.WinForms 窗体版以及 接口化 WCF+CefSharp.WinForms的网站版本,可是因为某些缘由,延伸出Selenium学习与研究html
总结:selenium特色是在作自动化测试,若是公司须要自动化测试是个不错的选择,开发语言包含不少。你彻底能够使用本身熟悉的语言进行开发,请查看 https://docs.seleniumhq.org/docs/ 经过几天的摸索,我的比较仍是建议你们最后部署在windows平台,linux平台因为缺乏可视化,在调试的时候会有不少坑。java
1.C#调用seleniumpython
请参照 http://www.mamicode.com/info-detail-2746933.htmlmysql
一、咱们新建一个C#控制台程序linux
二、使用Nuget搜索如下依赖库web
须要引用的核心库是Selenium.RC,Selenium.Support,Selenium.WebDriverspring
MvcWeb版也能够运行,挂在IIS能够很好运行sql
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); } } } }
2.Java调用seleniumchrome
使用Maven导入包shell
<!-- 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())); } } }
Linux运行selenium
1.须要在Linux上面安装Chrome 参考 https://www.cnblogs.com/z-x-y/p/9506941.html
一、安装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
二、安装 chromedriver
chrome官网 wget https://chromedriver.storage.googleapis.com/2.38/chromedriver_linux64.zip
淘宝源(推荐)wgethttp://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()
代码执行后会自动运行谷歌浏览器,并打开设置的网址,而后进行帐号和密码登陆