自定义代码项目,WebBrowser相关,在C#中找不到特定id的元素

时间:2012-10-09 11:55:10

标签: c# html console getelementbyid

我一直在控制台项目上开发基于C#的Web浏览器相关程序。现在,这是一段在 Windows窗体应用程序中工作的代码,但在控制台应用程序中,它向我显示'对象引用未设置为对象的实例' 。到目前为止,通过调试,将元素从 HTMLElementCollection 中的所有内容转移到 var ,它显示为False,这意味着HTML中没有这样的id。现在,这段代码没有错,因为相同的代码在Windows窗体应用程序中完美运行。我希望你明白。对此有点帮助将不胜感激!感谢。

下面提供了这段代码:

if (browser.ReadyState == WebBrowserReadyState.Complete)
{
    //Putting the values inside the boxes
    browser.Document.GetElementById("project_title").SetAttribute("value", projectTitle);
    browser.Document.GetElementById("article_title").SetAttribute("value", title);
    browser.Document.GetElementById("article_content").SetAttribute("value", content);
    browser.Document.GetElementById("article_tags").SetAttribute("value", tags);
    browser.Document.GetElementById("article_url_1").SetAttribute("value", url);
    browser.Document.GetElementById("article_keyword_1").SetAttribute("value", keywords);
    browser.Document.GetElementById("article_url_2").SetAttribute("value", url2);
    browser.Document.GetElementById("article_keyword_2").SetAttribute("value", keywords2);
    browser.Document.GetElementById("article_url_3").SetAttribute("value", url3);
    browser.Document.GetElementById("article_keyword_3").SetAttribute("value", keywords3);

    HtmlElementCollection lastElementCollection = browser.Document.All;
    foreach (HtmlElement webpageelement in lastElementCollection)
    {
        if (webpageelement.GetAttribute("value").Contains("Submit"))
            webpageelement.InvokeMember("click");
    }

    Console.WriteLine("Please wait for 5 second(s).");
    Thread.Sleep(5000);
    Console.WriteLine("Post has been submitted successfully!");
}

2 个答案:

答案 0 :(得分:1)

您确定浏览器对象已加载了正确的内容吗?首先检查browser.Document元素的innerHtml。 (虽然调试可能是?)

答案 1 :(得分:0)

你可以试试这个:

只需在代码段的第一个IF语句之前放置一个等待序列;像这样:

while (browser.ReadyState != WebBrowserReadyState.Complete)
{  
  Application.DoEvents();
}

if (browser.ReadyState == WebBrowserReadyState.Complete)
{
...

<强>更新: 您使用的是DocumentCompleted事件吗?使用您请求的URL检查WebBrowserDocumentCompletedEventArgs的url属性是否相同。因为documentcompleted会触发Web请求中的所有文件(例如js和css文件)。