1.环境准备
1.1 开发工具
Visual Studio 2017?
1.2 驱动下载地址
Chrome驱动下载地址:https://npm.taobao.org/mirrors/chromedriver/
找到对应电脑的版本下载,比如我本机是Windows 操作系统、Chrome 92版本的,那下载地址就是https://npm.taobao.org/mirrors/chromedriver/92.0.4515.43/chromedriver_win32.zip
2.库安装
需要使用库的项目,右键->管理Nuget程序包
?
3.创建驱动对象
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Diagnostics;
using System.Linq;
/*
*┌────────────────────────────────────────────────┐
*│ 描 述:谷歌驱动类
*│ 作 者:1326702940@qq.com
*│ 版 本:1.0
*│ 创建时间:2021-8-25
*└────────────────────────────────────────────────┘
*/
namespace ChromeDriver
{
/// <summary>
///
/// </summary>
public class ChromeDriver
{
/// <summary>
/// 获取Chrome驱动对象
/// </summary>
/// <param name="WebDriverPath">IEDriverServer.exe 的存放路径</param>
/// <returns></returns>
public IWebDriver GetChromeDriver(string WebDriverPath = "", ChromeOptions options = null)
{
if (string.IsNullOrWhiteSpace(WebDriverPath))
{
WebDriverPath = ".";
}
if (options == null)
{
options = new ChromeOptions();
// 隐藏Chrome 正在受到自动化软件控制,避免前端检测 76之前的写法
options.AddArgument("disable-infobars");
// 隐藏Chrome 正在受到自动化软件控制,避免前端检测 76之后的写法
options.AddExcludedArgument("enable-automation");
options.AddAdditionalCapability("useAutomationExtension", false);
// 设置每次下载时,弹窗选择下载路径
options.AddUserProfilePreference("download.prompt_for_download", true);
}
var service = ChromeDriverService.CreateDefaultService(WebDriverPath);
service.HideCommandPromptWindow = true;
var driver = new OpenQA.Selenium.Chrome.ChromeDriver(service, options);
if (driver != null)
{
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().PageLoad = TimeSpan.FromMilliseconds(60000);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(1500);
driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromMilliseconds(60000);
}
return driver;
}
/// <summary>
/// 关闭驱动
/// </summary>
public void CloseChromeDriver()
{
Process[] pros = Process.GetProcessesByName("chromedriver");
if (pros.Length > 10)
{
var prosOrder = pros.OrderBy(item => { return item.StartTime; }).ToArray();
for (int i = 10; i < prosOrder.Length; i++)
{
prosOrder[i].Kill();
}
}
}
}
}
4.驱动页面元素
using Common;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.Events;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
/*
*┌────────────────────────────────────────────────┐
*│ 描 述:Chrome驱动示例Demo
*│ 作 者:1326702940@qq.com
*│ 版 本:1.0
*│ 创建时间:2021-8-27
*└────────────────────────────────────────────────┘
*/
namespace ChromeDriver
{
/// <summary>
/// 应用demo
/// 驱动下载地址 https://npm.taobao.org/mirrors/chromedriver/
/// 测试实验 92 版本
/// </summary>
public class ChromeDriverDemo
{
ChromeDriver iEDriver = new ChromeDriver();
/// <summary>
/// 测试Demo
/// </summary>
public void LoginTest()
{
// 驱动对象
IWebDriver idriver = iEDriver.GetChromeDriver();
// 页面事件监听
EventFiringWebDriver driver = new EventFiringWebDriver(idriver);
// 执行js对象
IJavaScriptExecutor jsExec = (IJavaScriptExecutor)driver;
// 点击监听
driver.ElementClicked += Driver_ElementClicked;
// 导航监听
driver.NavigatedForward += Driver_NavigatedForward;
// 弹个窗
jsExec?.ExecuteScript("alert('我是警告框');");
// 点击 警告框的 确定 按钮
driver.SwitchTo()?.Alert()?.Accept();
// 导航到测试网址
driver.Navigate().GoToUrl("https://yxyh.aicenyi.com/");
#region 如果元素位于iframe里
try
{
IWebElement iframe = WaitUntilElement(driver, By.XPath("//*[@id=\"loginIframe\"]"));
// 进入到iframe
driver.SwitchTo().Frame(iframe);
// 一顿操作猛如虎
// 释放iframe,重新回到主页面上
driver.SwitchTo().DefaultContent();
}
catch (Exception ex)
{
;
}
#endregion
// 输入用户名
WaitUntilElement(driver, By.Id("userName"))?.SendKeys("admin");
Thread.Sleep(1000);
// 输入密码
WaitUntilElement(driver, By.Id("password"))?.SendKeys("123456");
// 截图前这个操作并非必须,只是为了展示更多知识点
// 移动鼠标到验证码元素上
Actions action = new Actions(driver);
var imageObjElement = WaitUntilElement(driver, By.Id("imgObj"));
action?.MoveToElement(imageObjElement);
// 获取验证码坐标
var point = Point.Empty;
point.X = (imageObjElement?.Location.X).Value;
point.Y = (imageObjElement?.Location.Y).Value;
// 获取验证码宽高
var size = Size.Empty;
size.Width = (imageObjElement?.Size.Width).Value;
size.Height = (imageObjElement?.Size.Height).Value;
// 根据屏幕缩放计算真实值 如果屏幕无缩放,不需要这样处理
int offsetX = GetScreenOfZoom((decimal)point.X);
int offsetY = GetScreenOfZoom((decimal)point.Y);
int width = GetScreenOfZoom((decimal)size.Width);
int height = GetScreenOfZoom((decimal)size.Height);
// 验证码截图
ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
var picBytes = ImageHelper.GetPartOfImageRecFromBytes(screenshot.AsByteArray, width, height, offsetX, offsetY);
// 保存为本地图片
var picBytes2 = picBytes;
MemoryStream ms = new MemoryStream(picBytes2);
Image img = Image.FromStream(ms);
img.Save("cc.png");
img?.Dispose();
// 输入验证码
// 点击验证码输入框
var yzmElement = WaitUntilElement(driver, By.Id("imageCode"));
yzmElement?.Click();
yzmElement.SendKeys("验证码11");
// 点击登录
var loginElement = WaitUntilElement(driver, By.Id("loginBtn"));
loginElement?.Click();
iEDriver.CloseChromeDriver();
}
/// <summary>
/// 点击监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Driver_ElementClicked(object sender, WebElementEventArgs e)
{
Console.WriteLine("Driver_ElementClicked");
}
/// <summary>
/// 导航监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Driver_NavigatedForward(object sender, WebDriverNavigationEventArgs e)
{
Console.WriteLine("Driver_NavigatedForward");
}
/// <summary>
/// 等待
/// </summary>
/// <param name="driver">驱动</param>
/// <param name="by">选择器</param>
/// <param name="timeWait">等待事件 毫秒</param>
/// <returns></returns>
public IWebElement WaitUntilElement(IWebDriver driver, By by, int timeWait = 1000)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(timeWait));
return wait.Until(dri => dri.FindElement(by));
}
/// <summary>
/// 拖动元素 针对元素
/// </summary>
/// <param name="driver">驱动</param>
/// <param name="element">要拖动的元素</param>
/// <param name="offsetX">X轴方向的距离</param>
/// <param name="offsetY">Y轴方向的距离</param>
public void HoldAndMove(IWebDriver driver, IWebElement element, int offsetX, int offsetY)
{
Actions action = new Actions(driver);
action?.ClickAndHold(element).Perform();
action?.MoveByOffset(offsetX, offsetY).Perform();
if (!driver.ToString().Equals("OpenQA.Selenium.IE.InternetExplorerDriver"))
{
// 非IE 取消 点击
action?.Click()?.Perform();
}
// 释放
action?.Release()?.Perform();
}
/// <summary>
/// 根据缩放计算相对于屏幕的实际尺寸
/// </summary>
/// <param name="value">原始值</param>
/// <returns></returns>
public int GetScreenOfZoom(decimal value)
{
return Convert.ToInt32(Math.Round((decimal)ScreenUtils.ScaleDpiX * value, 0, MidpointRounding.AwayFromZero));
}
}
}
|