gpt4 book ai didi

C#.net 从控制台使用 HTMLDocument?

转载 作者:太空狗 更新时间:2023-10-30 00:36:29 26 4
gpt4 key购买 nike

我正在尝试使用 System.Windows.Forms.HTMLDocument在控制台应用程序中。首先,这可能吗?如果是这样,我如何将网页从网络加载到其中?我正在尝试使用 WebBrowser ,但它告诉我:

Unhandled Exception: System.Threading.ThreadStateException: ActiveX control '885 6f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current th read is not in a single-threaded apartment.

HTMLDocument 似乎严重缺乏教程对象(或者 Google 只是出现了无用的结果)。


刚刚发现mshtml.HTMLDocument.createDocumentFromUrl , 但这让我很吃惊

Unhandled Exception: System.Runtime.InteropServices.COMException (0x80010105): T he server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERF AULT)) at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFla gs flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) at mshtml.HTMLDocumentClass.createDocumentFromUrl(String bstrUrl, String bstr Options) at 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);
}
}
}
}

最佳答案

作为替代方案,您可以使用免费的 Html Agility Pack图书馆。它可以解析 HTML 并让您使用 LINQ 查询它。我在家里的项目中使用了旧版本,效果很好。

编辑:您可能还想使用 WebClient 或 WebRequest 类来下载网页。请参阅我在 Web scraping in .NET 上的博客文章. (请注意,我还没有在控制台应用程序中尝试过。)

关于C#.net 从控制台使用 HTMLDocument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1777799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com