相对于 HTML 中的绝对路径

2023-11-24

我需要通过 URL 创建新闻通讯。为此,我:

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

但是,我在路径方面遇到了一些麻烦。所有元素的来源都是相对的(/img/welcome.png)但我需要一个绝对的,比如http://www.example.com/img/welcome.png.

我怎样才能做到这一点?


解决此任务的可能方法之一是使用Html敏捷包图书馆。

一些例子(修复链接):

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);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

相对于 HTML 中的绝对路径 的相关文章