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 最终效果如下动图所示:

 

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 System.Diagnostics.Process 类来检查系统中是否有指定的进程在运行。首先,你需要获取到指定浏览器的进程名称。例如,IE浏览器的进程名称为 iexplore.exe。然后,你可以使用 Process.GetProcessesByName 方法来获取指定名称的所有进程,然后遍历这些进程,检查它们的主窗口句柄是否包含指定的 URL。 以下是一个示例代码,用于检查 IE 浏览器是否已经打开了指定的 URL: ```csharp using System.Diagnostics; public static bool IsUrlOpened(string url) { string processName = "iexplore"; // IE浏览器的进程名称 Process[] processes = Process.GetProcessesByName(processName); foreach (Process process in processes) { IntPtr handle = process.MainWindowHandle; if (handle != IntPtr.Zero) { string windowUrl = GetUrlFromWindowHandle(handle); if (windowUrl == url) { return true; } } } return false; } private static string GetUrlFromWindowHandle(IntPtr handle) { const int maxUrlLength = 2048; StringBuilder sb = new StringBuilder(maxUrlLength); int length = NativeMethods.GetWindowText(handle, sb, maxUrlLength); if (length > 0) { string windowTitle = sb.ToString(); if (windowTitle.StartsWith("about:") || windowTitle.StartsWith("http")) { return windowTitle; } } return string.Empty; } internal static class NativeMethods { [DllImport("user32.dll", CharSet = CharSet.Auto)] internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); } ``` 上面的代码中,我们使用了 `GetProcessesByName` 方法来获取所有名为 iexplore 的进程。然后,我们遍历这些进程的主窗口句柄,通过 `GetWindowText` 方法获取窗口标题,从而判断窗口是否包含指定的 URL。 请注意,这种方法有一些限制。首先,它仅适用于 IE 浏览器,如果你想检查其他浏览器是否打开了指定的 URL,你需要修改进程名称。此外,这种方法还可能会误判,因为一个浏览器窗口可以同时包含多个标签页,每个标签页可能包含不同的 URL,我们只能获取窗口的标题,无法精确判断哪个标签页包含指定的 URL

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值