【发布时间】:2009-11-22 04:21:47
【问题描述】:
我正在尝试在控制台应用程序中使用System.Windows.Forms.HTMLDocument。首先,这可能吗?如果是这样,我如何将网页从网络加载到其中?我试图使用WebBrowser,但它告诉我:
未处理的异常: System.Threading.ThreadStateException: ActiveX 控件'885 6f961-340a-11d0-a96b-00c04fd705a2' 无法实例化,因为 当前读取不在 单线程单元。
似乎严重缺乏关于 HTMLDocument 对象的教程(或者 Google 只是发现了无用的结果)。
刚刚发现mshtml.HTMLDocument.createDocumentFromUrl,但这让我很震惊
未处理的异常: System.Runtime.InteropServices.COMException (0x80010105): 服务器抛出了一个 例外。 (HRESULT 的例外情况: 0x80010105 (RPC_E_SERVERF AULT)) 在 System.RuntimeType.ForwardCallToInvokeMember(字符串 memberName,BindingFla gs 标志, 对象目标,Int32[] aWrapperTypes, 消息数据和消息数据)在 mshtml.HTMLDocumentClass.createDocumentFromUrl(字符串 bstrUrl,字符串 bstr 选项)在 iget.Program.Main(String[] args)
什么鬼?我想要的只是页面上的<a> 标签列表。为什么这么难?
对于那些好奇的人,这是我想出的解决方案,感谢TrueWill:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using HtmlAgilityPack;
namespace iget
{
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
HtmlDocument doc = new HtmlDocument();
doc.Load(wc.OpenRead("http://google.com"));
foreach(HtmlNode a in doc.DocumentNode.SelectNodes("//a[@href]"))
{
Console.WriteLine(a.Attributes["href"].Value);
}
}
}
}
【问题讨论】: