从webbrowser获取文档文本

时间:2014-12-24 02:24:31

标签: c# webbrowser-control

我有以下代码,这只是为了从网站上获取文档文本,但我无法使其工作。似乎永远不会调用文档完成方法(PrintDocument)。控制台只是打开并坐在那里,没有任何东西被打印到屏幕上。

    class BrowserControl
{
    public void PrintHelpPage()
    { 
        WebBrowser webBrowserForPrinting = new WebBrowser();

        webBrowserForPrinting.DocumentCompleted +=
            new WebBrowserDocumentCompletedEventHandler(PrintDocument);

        webBrowserForPrinting.Url = new Uri("http://www.fooweb.com");
    }

    public void PrintDocument(object sender,
        WebBrowserDocumentCompletedEventArgs e)
    {
        // Print the document now that it is fully loaded.
        string test = ((WebBrowser)sender).DocumentText;

        Console.WriteLine(test);
        Console.WriteLine("DONE! ---------------------");

    }
}


    class Program
{

    public static void Main(string[] args)
    {
        BrowserControl browser = new BrowserControl();

        Thread browserThread = new Thread(browser.PrintHelpPage);
        browserThread.SetApartmentState(ApartmentState.STA);
        browserThread.Start();

        Console.ReadKey();

    }
}

1 个答案:

答案 0 :(得分:0)

听起来你忘记了实际导航到文档。

此处缺少一些内容,但主要内容是调用.Navigate()而不是.Url,并使用Application.DoEvents()或类似的调用来保持事件管道的运行,直到文档为满载。

第一,我建议您在STAThreadAttribute入口点使用Main(),而不是将ApartmentState.STA应用于单个帖子。它可能仍然按照您的方式工作,但在过去,我总是使用属性:

[STAThread]
public static void Main(string[] args)
{
    BrowserControl browser = new BrowserControl();

其次,如果你想要发生某些事情,你真的需要使用WebBrowser.Navigate(url)

    webBrowserForPrinting.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(PrintDocument);

    webBrowserForPrinting.Navigate("http://www.fooweb.com");
}

第三,要加载文档并执行DocumentCompleted处理程序,您需要按如下方式运行事件管道:

    webBrowserForPrinting.Navigate("http://www.fooweb.com");

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

另外,别忘了开始行动:

class Program
{
  [STAThread]
  public static void Main(string[] args)
  {
    BrowserControl browser = new BrowserControl();
    browser.PrintHelpPage();

    Console.ReadKey();

  }
}

希望这很有用。 Cherio。