相对于HTML中的绝对路径(asp.net)

jo_*_*ura 7 html asp.net relative-path absolute-path

我需要通过URL创建新闻简报.我要做下一个:

  1. 创建WebClient;
  2. 使用WebClient的方法DownloadData获取字节数组中的页面源;
  3. 从source-html字节数组中获取字符串并将其设置为新闻稿内容.

但是我对路径有些麻烦.所有元素的来源都是相对的(/img/welcome.png),但我需要绝对(http://www.mysite.com/img/welcome.png).

我怎样才能做到这一点?

最好的问候,Alex.

jo_*_*ura 6

解决此任务的一种可能方法是使用HtmlAgilityPack库.

一些例子(修复链接):

WebClient client = new WebClient();
byte[] requestHTML = client.DownloadData(sourceUrl);
string sourceHTML = new UTF8Encoding().GetString(requestHTML);

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(sourceHTML);

foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//a[@href]"))
{
    if (!string.IsNullOrEmpty(link.Attributes["href"].Value))
    {
        HtmlAttribute att = link.Attributes["href"];
        att.Value = this.AbsoluteUrlByRelative(att.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我的脚本找不到这个.AbsoluteUrlByRelative (3认同)