webBrowser1.Navigate("http://hi.baidu.com/go/login");
Thread.Sleep(5000);
HtmlElementCollection inputs = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement input in inputs)
{
if (input.Id == "TANGRAM__PSP_3__userName")
{
    input.InnerText = "galaxy";
}
if (input.Id.ToLower() == "TANGRAM__PSP_3__password".ToLower())
{
    input.InnerText = "123456";
}
}
HtmlElement btn = webBrowser1.Document.GetElementById("TANGRAM__PSP_3__submit");
btn.InvokeMember("click");运行后总出错:未将对象引用设置到对象的实例。怎么回事啊?那位大侠请指教下啊webBrowser

解决方案 »

  1.   

    网页没加载完毕,代码放到doucmentcompleted事件里面执行或者消息队列while(webbrowser.readstate!=webbrowserreadstate.complted) application.doevent();都可以
      

  2.   


    webBrowser1.Navigate(new Uri("http://www.baidu.com/"));
                //GetLinksFromFrames();
                //MessageBox.Show(webBrowser1.Document.Window.Document.Body.InnerHtml);
                HtmlWindow htmlwin = webBrowser1.Document.Window;
                HtmlDocument doc = webBrowser1.Document;
                IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;
                vDocument.parentWindow.execScript("function confirm(){alert('111');} ", "javascript");            foreach (HtmlElement pageElement in webBrowser1.Document.All)
                {
                    Type type = pageElement.GetType();
                    string strName = pageElement.Name;
                    string strTagName = pageElement.TagName;
                    
                    foreach (HtmlElement ele in pageElement.GetElementsByTagName("INPUT"))
                    {
                        System.Console.WriteLine("标记:" + ele.OuterHtml);
                        IHTMLElement h2 = ele.DomElement as IHTMLElement;                    if (ele.Name == "wd")
                        {
                            ele.InnerText = "大写字母";
                        }
                        string strValue =  h2.getAttribute("value");
                        if (strValue == "百度一下")
                        {
                            //h2.setAttribute("value", "大写字母");
                            //HtmlElement buttonchaxun = this.webBrowser1.Document.All["Submit3"];
                            //buttonchaxun.InvokeMember("click");
                            ele.InvokeMember("click");
                        }
                       
                    }
                    //System.Console.WriteLine("名字:"+strName);
                    //System.Console.WriteLine("tag:" + strTagName);
                    //System.Console.WriteLine("标记:" + pageElement.InnerHtml);
                }
                doc.InvokeScript("confirm");
                
               // HtmlDocument doc = (HtmlDocument)webBrowser1.Document.DomDocument;      
      

  3.   

    需要引用系统中的using mshtml;
      

  4.   

    百度的登录form是通过js动态生成的,你这种直接Sleep会阻塞js的加载和执行,所以下面找不到元素。应该在DocumentCompleted里面处理。
    另,submit知道用GetElementById,上面的username和password怎么不用呢?