C#操控chrome和IE,Selenium

1、安装

在项目名\引用\右击\管理NuGet程序包\搜索Selenium

1.1安装核心库Selenium.Support 从安装输出中看到Selenium.WebDriver已经自动安装了

1.2安装 Chrome浏览器驱动库,程序包名称为Selenium.WebDriver.ChromeDriver。(没装最新的,根据我的浏览器版本选了一个79.0.3945的)安装完毕会在项目debug目录生成chromedriver.exe.

如果操控IE,则从NuGet下载安装Selenium.WebDriver.IEDriver

令人不解的是在项目的packages目录中会出现Baidu.AI.3.6.3,难道百度在这里面作了什么贡献?

2、代码:

 using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver())
            {
                driver.Navigate().GoToUrl("http://www.baidu.com");  //driver.Url = "http://www.baidu.com"是一样的

                var source = driver.PageSource;

                Console.WriteLine(source);
            }

编译,运行,成功打开chrome访问百度。

操控IE时用: using (var driver = new OpenQA.Selenium.IE.InternetExplorerDriver())

但是提示:

System.InvalidOperationException:“Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (SessionNotCreated)”

以前好像也遇到过类似提示,解决办法是在IE设置中将所有区域(包括受信任的)都统一设置成保护模式(或非保护模式)。

配置部分:

ChromeDriverService driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;//关闭黑色cmd窗口
 
ChromeOptions options = new ChromeOptions();
// 不显示浏览器
//options.AddArgument("--headless");
// GPU加速可能会导致Chrome出现黑屏及CPU占用率过高,所以禁用
options.AddArgument("--disable-gpu");
// 伪装user-agent
options.AddArgument("user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1");
// 设置chrome启动时size大小
options.AddArgument("--window-size=414,736");
// 禁用图片
options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
 
IWebDriver webDriver = new ChromeDriver(driverService,options);
//如果查找元素在5S内还没有找到
webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);  
string url = "https://www.baidu.com";
webDriver.Navigate().GoToUrl(url);

执行JS(将滚动条拉到底部):

((IJavaScriptExecutor)webDriver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");

获取标签(以多Class为例):

ReadOnlyCollection<IWebElement> elements = webDriver.FindElements(By.CssSelector("[class='item goWork']"));

退出同时关闭驱动

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if (webDriver!=null){
        //窗口关闭前记得浏览器,否则驱动会残留在进程里面
        webDriver.Quit();
    }
}

IE的话考虑这里注册表设置:https://stackoverflow.com/questions/23782891/selenium-webdriver-on-ie11 ,但是感觉还不如用微软自己的SHDocVw.InternetExplorer稳定可靠。

参考:https://blog.csdn.net/a1003434346/article/details/80257946

https://www.cnblogs.com/zhaotianff/p/11330810.html

https://blog.csdn.net/qq_34659777/article/details/82788465

https://blog.csdn.net/PLA12147111/article/details/92000480

https://www.cnblogs.com/baihuitestsoftware/articles/4682267.html