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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM