等待页面加载到Webbrowser C#

时间:2018-07-19 15:27:27

标签: c# browser

我有一个测试网页的程序-单击Web元素。  我正在使用C#WebBrowswer控件,但是在将文本插入文本字段之前遇到问题,我想等待页面加载。  等待页面加载,我正在使用:

    while (true)
    {
    System.Windows.Forms.Application.DoEvents();
        foreach (HtmlElement el in web_Browser.Document.GetElementsByTagName("р"))
        {
            if (el.GetAttribute("title") == "Custom") != null)
            {
                break;
            }
        }
    }

但是我在一行中得到一个错误:var elmC = web_Browser.Document.GetElementsByTagName(“ input”);  “检测到无法访问的代码”

        public void GetStatus(string innerText)
        {
            try
            {
                while (true)
                {
                    System.Windows.Forms.Application.DoEvents();
                    foreach (HtmlElement el in web_Browser.Document.GetElementsByTagName("р"))
                    {
                        if (el.GetAttribute("title") == "Custom") != null)
                        {
                           break;
                        }
                    }
                }


                var elmC = web_Browser.Document.GetElementsByTagName("input");
                foreach (HtmlElement elm in elmC)
                {
                    if (elm.Id == "num")
                    {
                        elm.InnerText = String.Empty;
                        Wait(1);
                        elm.InnerText = innerText;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " + ex.Message);
            }
        }

1 个答案:

答案 0 :(得分:1)

您的休息时间;语句只会从foreach循环中退出,而不是while(true)循环中,因此该循环将永远运行,之后的任何代码都无法访问...

也许可以尝试:

var run = true;

 while (run)
                {
                    System.Windows.Forms.Application.DoEvents();
                    foreach (HtmlElement el in web_Browser.Document.GetElementsByTagName("р"))
                    {
                        if (el.GetAttribute("title") == "Custom") != null)
                        {
                           run = false;
                        }
                    }
                }

但是通常任何读取“ while(){//检查异步操作}”的代码通常都是不好的...考虑使用事件或Thread.sleep()也许