selenium+C# 学习日记 初始化
1.新建项目
- 为什么选择单元测试项目而不是普通的类库项目?主要是考虑到方便进行调试,这种测试项目中可右键点击运行测试进行测试,而不用使用F5运行整改程序,比较方便快捷。
2.添加NuGet包
- 选择下面NuGet包即可(如果是需要控制IE浏览器,还需添加对应的driver包),之前试过单独下载安装chrome浏览器驱动,但是现在觉得麻烦,所以都是直接通过NuGet包进行配置;
下面是对应的驱动下载地址,喜欢自己配置或者是python的可以自行下载
- Chrome各版本浏览器驱动下载地址:http://chromedriver.storage.googleapis.com/index.html
- Firefox各版本浏览器驱动下载地址:https://github.com/mozilla/geckodriver/releases/
3.测试是否selenium是否正常
引用(一开始的时候没有using selenium,代码没有提示异常,但是浏览器没有响应;后续的时候添加了Selenium.RC这个NuGet包+using selenium之后才正常运行)--这个地方好坑
//Webdriver引用 using Selenium;//引用Selenium using OpenQA.Selenium; using OpenQA.Selenium.Chrome;//支持Chrome
代码体
IWebDriver driver = new ChromeDriver(); //访问百度 driver.Navigate().GoToUrl("https://www.baidu.com"); //查找搜索输入框,输入Selenium IWebElement searchText = driver.FindElement(By.Id("kw")); //在输入前清空内容 searchText.Clear(); searchText.SendKeys("Selenium"); //查找元素 IWebElement searchBtn = driver.FindElement(By.Id("su")); //点击搜索按钮 searchBtn.Click(); //退出浏览器 driver.Close();