【问题标题】:How do I form complete URLs from incomplete URLs found in a web page?如何从网页中找到的不完整 URL 形成完整的 URL?
【发布时间】:2010-10-24 01:15:09
【问题描述】:

我可以检索网页的文本,比如说https://stackoverflow.com/questions,其中包含一些真实的和虚构的链接:

/问题 /标签 /questions?sort=votes /questions?sort=active 随机页面.aspx ../coolhomepage.aspx

知道我的原始页面是https://stackoverflow.com/questions .Net 中是否有办法解决指向此的链接?

https://stackoverflow.com/questions https://stackoverflow.com/tags https://stackoverflow.com/questions?sort=votes https://stackoverflow.com/questions?sort=active https://stackoverflow.com/questions/randompage.aspx https://stackoverflow.com/coolhomepage.aspx

有点像浏览器足够聪明地解析链接的方式。

=========================== 更新 - 使用大卫的解决方案:

'正则表达式匹配所有 链接 Dim myRegEx As New Regex("\.*?)['""] (?# Then all to the next ' or "") " & _ ".*?\> (?# 然后全部到 > ) " & _ "(?.*?)\ (?# Then all to ) ", _ RegexOptions.IgnoreCase 或 _ RegexOptions.IgnorePatternWhitespace 或 _ 正则表达式选项。多行) 'MatchCollection 保存所有匹配的链接 将 myMatchCollection 调暗为 MatchCollection myMatchCollection = myRegEx.Matches(Me._RawPageText) '遍历所有匹配并评估 href 属性的值。 For i As Integer = 0 To myMatchCollection.Count - 1 将 thisLink 调暗为 String = "" thisLink = myMatchCollection(i).Groups("href").Value() '这会检查 Javascript 和 Mailto 链接。 '这并不完整。还有其他要检查的,我只是还没有遇到过。 如果 thisLink.ToLower.StartsWith("javascript") 那么 thisLink = "JAVASCRIPT:" & thisLink ElseIf thisLink.ToLower.StartsWith("mailto") Then thisLink = "MAILTO:" & thisLink 别的 将 baseUri 调暗为新 Uri(Me.URL) If Not thisLink.ToLower.StartsWith("http") Then '这是一个部分 URL,所以我们假设它是相对于我们的原始 URL 将 myUri 调暗为新 Uri(baseUri, thisLink) thisLink = "相对本地链接:已解决:" & myUri.ToString() & " ORIGINAL: " & thisLink 别的 '链接以 HTTP 开头,确定是基本主机的一部分还是在主机之外。 将 ThisUri 调暗为新的 Uri(thisLink) 如果 ThisUri.Host.ToLower = baseUri.Host.ToLower Then thisLink = "内部完整链接:" & thisLink 别的 thisLink = "外部链接:" & thisLink 万一 万一 万一 '我将找到的链接存储到 Generic.List(Of String) '此链接添加了描述性文本。 'TODO:使集合仅包含唯一的内部链接。 Me._Links.Add(thisLink) 下一个

【问题讨论】:

    标签: .net asp.net url hyperlink resolve


    【解决方案1】:

    你的意思是这样的?

    Uri baseUri = new Uri("http://www.contoso.com");
    Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
    
    Console.WriteLine(myUri.ToString());
    

    样本来自http://msdn.microsoft.com/en-us/library/9hst1w91.aspx

    【讨论】:

    • 是的,这正是我所需要的。这适用于来自不同位置的 URL。我将更新我的问题以展示我是如何实现它的。谢谢!
    【解决方案2】:

    我不明白你在这种情况下所说的“解决”是什么意思,但你可以尝试插入一个基本的 html 元素。既然你问浏览器将如何处理它。

    <base> 标记为页面上的所有链接指定默认地址或默认目标。”

    http://www.w3schools.com/TAGS/tag_base.asp

    【讨论】:

      【解决方案3】:

      如果你指的是服务器端,你可以使用ResolveUrl():

      string url = ResolveUrl("~/questions");
      

      【讨论】:

        猜你喜欢
        • 2011-04-14
        • 2015-07-21
        • 1970-01-01
        • 2017-08-13
        • 1970-01-01
        • 1970-01-01
        • 2011-05-13
        • 2022-11-16
        • 2012-11-06
        相关资源
        最近更新 更多