我需要通过URL创建新闻组。我下一步做:相对于HTML中的绝对路径(asp.net)
- 创建一个WebClient;
- 使用WebClient的方法 DownloadData以字节数组形式获取页面 的源文件;
- 从source-html字节获取字符串 数组并将其设置为简讯 的内容。
但我有一些路径的麻烦。所有元素的来源都是相对的(/img/welcome.png),但我需要绝对的(http://www.mysite.com/img/welcome.png)。
我该怎么做?
此致敬礼,亚历克斯。
我需要通过URL创建新闻组。我下一步做:相对于HTML中的绝对路径(asp.net)
但我有一些路径的麻烦。所有元素的来源都是相对的(/img/welcome.png),但我需要绝对的(http://www.mysite.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);
}
}
你有一些选择:
Console.Write(ControlChars.Cr + "Please enter a Url(for example, http://www.msn.com): ") Dim remoteUrl As String = Console.ReadLine() Dim myWebClient As New WebClient() Console.WriteLine(("Downloading " + remoteUrl)) Dim myDatabuffer As Byte() = myWebClient.DownloadData(remoteUrl) Dim download As String = Encoding.ASCII.GetString(myDataBuffer) download.Replace("src=""/", "src=""" & remoteUrl & "/") download.Replace("href=""/", "href=""" & remoteUrl & "/") Console.WriteLine(download) Console.WriteLine("Download successful.")
这是超级做作,实际上它的主要冲击是直接取自:http://msdn.microsoft.com/en-us/library/xz398a3f.aspx,但它说明了背后的方法1.
谢谢,我知道这样的方式,但我希望有一些更容易的方法来做到这一点=) – 2010-04-27 07:41:12
的基本原则,如果请求从您的网站进来(同域名链接),那么你可以使用这个:
new Uri(Request.Uri, "/img/welcome.png").ToString();
如果你在非Web应用程序,或者你想硬编码域名:
new Uri("http://www.mysite.com", "/img/welcome.png").ToString();
我需要在html中替换所有元素的src和href我不仅得到一个路径。 – 2010-04-27 07:36:36
只要使用此功能
'# converts relative URL ro Absolute URI
Function RelativeToAbsoluteUrl(ByVal baseURI As Uri, ByVal RelativeUrl As String) As Uri
' get action tags, relative or absolute
Dim uriReturn As Uri = New Uri(RelativeUrl, UriKind.RelativeOrAbsolute)
' Make it absolute if it's relative
If Not uriReturn.IsAbsoluteUri Then
Dim baseUrl As Uri = baseURI
uriReturn = New Uri(baseUrl, uriReturn)
End If
Return uriReturn
End Function
而不是解决所/完成相对路径,你可以尝试设置与基本元素href-attrib =有问题的原始baseURI。
作为标题元素的第一个子元素,所有跟随的相对路径应该由浏览器解析为指向原始目标,而不是doc(通讯)所在/来自的位置。
关于firefox,一些重言式(<-在正式逻辑中)所有src/href-attribs的获取/设置的往返恢复为将完整路径写入html-doc的所有图层(序列化)因此可编写脚本,可保存...:
var d=document;
var n= d.querySelectorAll('[src]'); // do the same for [href] ...
var i=0; var op ="";var ops="";
for (i=0;i<n.length;i++){op = op + n[i].src + "\n";ops=n[i].src;
n[i].src=ops;}
alert(op);
当然,URL() - 作为风格元素给FUNC基地(S, - 背景-IMG或内容规则),以及在样式ATTRIB的节点级和特别是url() - func-stated src/href-values不被上面的任何解决方案视为/测试。
因此,要获得有效的,经过测试的(compat-list)状态的base-Elem方法,对我来说似乎是更有希望的概念。
我的脚本没有找到这个.AbsoluteUrlByRelative – ram4nd 2012-05-06 12:33:31