C#操作IE瀏覽器(打開url、獲取瀏覽器地址欄的地址、模擬百度搜索)

下面的代碼參考 https://www.cnblogs.com/kissdodog/p/3725774.html,非我原創,所以就標爲轉載

注意:下面的方法只適用於系統自帶的IE瀏覽器,其它瀏覽器不適用,連360瀏覽器都不行

 

下面的程序實現三個功能

1  程序打開瀏覽器,並轉到對應url的網頁

2  獲取瀏覽器地址欄上所有的url地址

3  模擬百度輸入搜索

 

步驟如下:

1  新建一個控制檯項目,名爲'操作ie瀏覽器'

2  爲項目添加Microsoft Internet Controls.dll引用和Microsoft HTML Object Library引用,注意Microsoft Internet Controls.dll引用被添加後還要鼠標右擊它,設置它的 ‘嵌入互操作類型’ 屬,性爲False,不然會報錯

3 添加一個類 ,名爲IEOperation,並編輯如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 操作ie瀏覽器
{
    class IEOperation
    {
        /// <summary>
        /// 利用ie瀏覽器打開url地址,如果ie瀏覽器處於關閉狀態,則會打開ie瀏覽器並切換到url頁
        /// </summary>
        /// <param name="url">要打開的url地址</param>
        public void OpenUrl(string url) {
           
            //新建一個Tab,然後打開指定地址(方式1)
            //SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
           // SHDocVw.InternetExplorer webBrowser1 = (SHDocVw.InternetExplorer)shellWindows.Item(shellWindows.Count - 1);
           // webBrowser1.Navigate(url);

            //System.Diagnostics.Process.Start("iexplore.exe");  //直接打開IE瀏覽器(打開默認首頁)
            System.Diagnostics.Process.Start("iexplore.exe",url);  //直接打開IE瀏覽器,打開指定頁
           
        }


        /// <summary>
        /// 獲取當前瀏覽器打開的所有url地址
        /// </summary>
        /// <returns>得到的url集合</returns>
        public List<string> GetUrlList() {
            System.Diagnostics.Process []process=System.Diagnostics.Process.GetProcesses();
            List<string> UrlList = null;
            //證明沒有啓動瀏覽器,爲了看到效果,默認啓動百度
            if (process.Where(pro => pro.ProcessName.Contains("iexplore")).Count() == 0)
            {
                System.Diagnostics.Process pro = System.Diagnostics.Process.Start("iexplore.exe", "www.baidu.com");
                pro.EnableRaisingEvents = true;           //啓用程序退出引發事件
                pro.Exited += delegate(object sender1, EventArgs e1)
                {
                    UrlList = GetUrlListMethod();

                };
            }
            else 
            {
                UrlList = GetUrlListMethod();
            }

            return UrlList;
        }

        /// <summary>
        /// 實際獲取的方法,因爲方法GetUrlList()中有兩個方法使用到了,就做了封裝
        /// </summary>
        /// <returns></returns>
        private List<string> GetUrlListMethod()
        {
            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            List<string> UrlList = new List<string>();
            //遍歷所有shellWindow
            foreach (SHDocVw.InternetExplorer ie in shellWindows)
            {
                string filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
                //測試發現有一個不是url地址,就是爲了過濾它
                if (filename.Equals("iexplore"))
                {

                    UrlList.Add(ie.LocationURL.ToString());
                }
            }
            return UrlList;
        }


        /// <summary>
        /// 通過DOM操作IE(本方法模擬百度輸入搜索)
        /// </summary>
        /// <param name="queryString"></param>
        public void OperationByDOM(string queryString) {
            System.Diagnostics.Process process= System.Diagnostics.Process.Start("iexplore.exe", "http://www.baidu.com");  //直接打開IE瀏覽器,打開指定頁

            process.EnableRaisingEvents = true;           //啓用程序執行完畢(或者退出)引發事件
            process.Exited += delegate(object sender1, EventArgs e1)
            {
                //在這裏編寫程序執行完畢後的業務邏輯
                Console.WriteLine("IE瀏覽器打開完畢,一定要這樣做");
                SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
                SHDocVw.InternetExplorer webBrowser1 = (SHDocVw.InternetExplorer)shellWindows.Item(shellWindows.Count - 1);


                //遍歷所有選項卡,看是否有百度的url
                foreach (SHDocVw.InternetExplorer Browser in shellWindows)
                {
                    if (Browser.LocationURL.Contains("www.baidu.com"))
                    {
                        //獲取百度的document,即拿到百度的html對象
                        mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)Browser.Document;
                       
                        //查找html頁面中所有的input標籤
                        mshtml.IHTMLElementCollection inputs = (mshtml.IHTMLElementCollection)doc2.all.tags("input");
                        //獲取所有input標籤中id號爲kw的標籤,即該標籤爲輸入框對應的id
                        mshtml.HTMLInputElement input1 = (mshtml.HTMLInputElement)inputs.item("kw", 0);
                        //爲輸入框賦值
                        input1.value = queryString;
                        //獲取所有input標籤中id號爲su的標籤,即爲 '百度一下' 那個按鈕對應的id
                        mshtml.IHTMLElement element2 = (mshtml.IHTMLElement)inputs.item("su", 0);
                        //模擬鼠標點擊 '百度一下' 那個按鈕
                        element2.click();
                        
                    }
                }
            };
            

            
        }

    }
}

 

3  主方法調用如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 操作ie瀏覽器
{
    class Program
    {
        static void Main(string[] args)
        {
            IEOperation operation = new IEOperation();
            //operation.OpenUrl("http://www.baidu.com");
            foreach (var item in operation.GetUrlList())
            {
               Console.WriteLine(item);
            }
            operation.OperationByDOM("加菲貓");
            Console.Read();

        }
    }
}

4 最終效果如下動圖所示:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章