2014-12-24 81 views
1

我有下面的代码,它只是简单地从网站上获取文档文本,但我无法让它工作。看起来文档完成方法(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(); 

    } 
} 

回答

0

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

这里有几个缺失的东西,但关键的是调用.Navigate()而不是.Url,并保持事件管道通过使用Application.DoEvents()或类似的调用,直到文档被完全加载。

1st我建议您在Main()入口处使用STAThreadAttribute,而不是将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。

+0

很好。这很有帮助。但是,运行此时我收到以下错误信息:无法获取'WebBrowser'控件的窗口句柄。不支持Windowless ActiveX控件。'从阅读其他答案,似乎我需要调用控件? – awwwyissss

+0

您可以在没有窗口的情况下使用WebBrowser控件。我在[triflejs.org](http://triflejs.org/)上使用它作为无头IE浏览器。我想你只是错过了对'browser.PrintHelpPage()'的调用 –

相关问题