C# 网页自动化之selenium




一、什么是网页自动化?

1. 网页自动化是用代码来操作浏览器去执行你想要操作的步骤,其实这种大多数是用于测试,用来写自动化来测试网页,对网站进行快速的回归测试。
二、用到那些技术?
1. selenium:我最开始接触该技术的时候,是用来做python爬虫的时候,因为selenium可以很容易的对网页数据进行分析和操作。
2. xpath: 该技术主要是针对于对页面元素进行分析,可以根据其子元素或者父元素进行对元素的操作。
3. C#:这个是我这次用来实验的后端语言,主要还是想看看这个语言能不能进行自动化的操作,果然还是没有让我失望。
三、安装需要用到的nuget包
1. 在NuGet中下载Selenium.Chrome.WebDriver(v2.45.0)和Selenium.WebDriver(v3.141.0),然后引用using OpenQA.Selenium;和using OpenQA.Selenium.Chrome;
2. 声明和实例一个ChromeDriver对象
IWebDriver driver = new ChromeDriver(System.AppDomain.CurrentDomain.BaseDirectory.ToString());

3. 定义事件驱动的方式有8种构造方法,具体如下:

ChromeDriver()、
ChromeDriver(ChromeDriverService service)指定初始化ChromeDriver的服务、
ChromeDriver(ChromeOptions options)指定ChromeDriver的选项、
ChromeDriver(string chromeDriverDirectory)指定ChromeDriver.exe的目录路径、
ChromeDriver(ChromeDriverService service,ChromeOptions options)、
ChromeDriver(string chromeDriverDirectory,ChromeOptions options)、
ChromeDriver(ChromeDriverService service,ChromeOptions options,TimeSpan commandTimeOut)指定了命令的等待执行时间、 ChromeDriver(string chromeDriverDirectory,ChromeOptions options,TimeSpan commandTimeOut)

4. ChromeOptions可设置的参数如下:

user-agent=“”  设置请求头的User-Agent

window-size=1366,768  设置浏览器窗口大小

headless  无界面运行

start-maximized  最大化运行

incognito  隐身模式

disable-javascript  禁用javascript

disable-infobars  禁用浏览器正在被自动化程序控制的提示

case:

var option = new ChromeOptions();
option.AddArgument("--incognito");
option.AddArgument("headless");
option.AddArgument("disable-infobars");
IWebDriver driver = new ChromeDriver(System.AppDomain.CurrentDomain.BaseDirectory.ToString(),option);

5. 打开网址和设置元素查找时间限制: 备注 :ImplicitWait是隐形等待时间,就是表示如果一旦找到该元素,就会继续向下执行。

driver.Navigate().GoToUrl("https://www.baidu,com");
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);

6. 获取html元素并进行操作

driver.FindElement(By.XPath("//button[@class=\"qweqwe"]")).Click();
IWebElement tryit;
tryit = driver.FindElement(By.XPath("//textarea[@class=\"qweqwad\"]"));
tryit.Clear();
tryit.SendKeys("{"wj":"qweadd"}");

第二种方式:

 driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
            driver.FindElement(By.XPath("//*[@]")).SendKeys("锦大大的博客园");
            driver.FindElement(By.Id("su")).Click();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(200);
            driver.FindElement(By.XPath("//*[@]/h3/a")).Click();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5000);
7. 如果返回多个就需要使用collection,引用using System.Collections.ObjectModel;
ReadOnlyCollection<IWebElement> coll = driver.FindElements(By.XPath("//*[@test"));
8. 其他一些可能使用的语句
driver.Manage().Window.Maximize();//窗口最大化
System.Threading.Thread.Sleep(1000);//等待1秒
ReadOnlyCollection<string> windows = driver.WindowHandles;
driver.SwitchTo().Window(windows[1]);//有新窗口弹出时切换