我需要通过 URL 创建新闻通讯。为此,我:
- 创建一个
WebClient
。 - 使用WebClient的方法
DownloadData
获取字节数组中的页面源; - 从 source-html 字节数组中获取字符串并将其设置为时事通讯内容。
但是,我在路径方面遇到了一些麻烦。所有元素的来源都是相对的 (/img/welcome.png
) 但我需要一个绝对来源,例如 http://www.example.com/img/welcome.png .
我该怎么做?
最佳答案
解决此任务的一种可能方法是使用 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);
}
}
关于asp.net - 相对于 HTML 中的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2719353/