在控制台应用程序中使用 WebBrowser

发布于 2024-11-15 05:51:48 字数 728 浏览 3 评论 0原文

我想用它来调用网页上的一些JS脚本。我有这个:

    static void Stuff()
    {
        WebBrowser browser = new WebBrowser();
        browser.Navigate("http://www.iana.org/domains/example/");
        HtmlDocument doc = browser.Document;
        //doc.InvokeScript("someScript");
        Console.WriteLine(doc.ToString());
    }

    static void Main(string[] args)
    {
        Console.WriteLine("hi");
        var t = new Thread(Stuff);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

问题 1:当我尝试获取 doc.ToString() 时,出现“对象引用未设置”异常。为什么?

问题2:如何从HTML文档中获取一些数据到主程序中? WebBrowser 需要一个单独的线程,该线程需要一个不能返回任何值的静态方法。例如,我如何将 doc 返回到 Main() 以便我可以用它做一些事情?

I want to use it to invoke some JS scripts on the webpage. I have this:

    static void Stuff()
    {
        WebBrowser browser = new WebBrowser();
        browser.Navigate("http://www.iana.org/domains/example/");
        HtmlDocument doc = browser.Document;
        //doc.InvokeScript("someScript");
        Console.WriteLine(doc.ToString());
    }

    static void Main(string[] args)
    {
        Console.WriteLine("hi");
        var t = new Thread(Stuff);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

Question 1: I get an "object reference not set" exception when I try to get doc.ToString(). Why?

Question 2: How do I get some data from the HTML document into the main program? WebBrowser requires a separate thread, which requires a static method which can't return any value. How do I return, say, doc to the Main() so I can do something with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

廻憶裏菂餘溫 2024-11-22 05:51:48

想法正确,执行错误。 WebBrowser.Navigate() 仅告诉网络浏览器开始导航到您请求的网页。这需要时间,通常需要数百毫秒。 Internet Explorer 在内部启动线程来完成工作。它通过引发 DocumentCompleted 事件来告诉您何时完成。你不用等待,所以首先是崩溃城市。

下一个问题是您的代码中不会引发 DocumentCompleted 事件。你必须遵守 STA 合约,它要求你启动消息循环。这是后台线程(例如 IE 用于检索网页的线程)告诉您的线程工作已完成的万能方式。

您需要的样板代码可在此答案中找到。

Right idea, wrong execution. The WebBrowser.Navigate() only tells the web browser to start navigating to the web page you asked for. That takes time, hundreds of milliseconds typically. Internet Explorer internally starts threads to get the job done. It tells you when it is done by raising the DocumentCompleted event. You don't wait for that so that's crash city first.

Next problem is that the DocumentCompleted event won't be raised in your code. You have to honor the STA contract, it requires you to pump a message loop. That's the all-mighty way that a background thread, like the one that IE uses to retrieve a web page, tells your thread that the job is done.

The boilerplate code you need is available in this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文