如何使用HtmlAgilityPack提取完整的URL - C#

Mon*_*RPG 8 c# hyperlink extraction html-agility-pack

好吧,下面的方式是只提取这样的引用网址

提取代码:

foreach (HtmlNode link in hdDoc.DocumentNode.SelectNodes("//a[@href]"))
{
    lsLinks.Add(link.Attributes["href"].Value.ToString());
}
Run Code Online (Sandbox Code Playgroud)

网址代码

<a href="Login.aspx">Login</a>
Run Code Online (Sandbox Code Playgroud)

提取的网址

Login.aspx
Run Code Online (Sandbox Code Playgroud)

但我想得到真正的链接浏览器解析

http://www.monstermmorpg.com/Login.aspx
Run Code Online (Sandbox Code Playgroud)

我可以检查网址是否包含http,如果没有添加域值,但在某些情况下可能会导致一些问题,我认为这不是一个非常明智的解决方案.

c#4.0,HtmlAgilityPack.1.4.0

Dun*_*art 15

假设您有原始网址,您可以将解析后的网址组合如下:

// The address of the page you crawled
var baseUrl = new Uri("http://example.com/path/to-page/here.aspx");

// root relative
var url = new Uri(baseUrl, "/Login.aspx");
Console.WriteLine (url.AbsoluteUri); // prints 'http://example.com/Logon.aspx'

// relative
url = new Uri(baseUrl, "../foo.aspx?q=1");
Console.WriteLine (url.AbsoluteUri); // prints 'http://example.com/path/foo.aspx?q=1'

// absolute
url = new Uri(baseUrl, "http://stackoverflow.com/questions/7760286/");
Console.WriteLine (url.AbsoluteUri); // prints 'http://stackoverflow.com/questions/7760286/'

// other...
url = new Uri(baseUrl, "javascript:void(0)");
Console.WriteLine (url.AbsoluteUri); // prints 'javascript:void(0)'
Run Code Online (Sandbox Code Playgroud)

请注意使用AbsoluteUri而不是依赖,ToString()因为ToString解码URL(使其更具"人类可读性"),这通常不是您想要的.