Как сформировать полные URL-адреса из неполных URL-адресов, найденных на веб-странице? - PullRequest
1 голос
/ 06 мая 2009

Я могу получить текст веб-страницы, скажем, https://stackoverflow.com/questions с некоторыми реальными и вымышленными ссылками:

    /questions
    /tags
    /questions?sort=votes
    /questions?sort=active
    randompage.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

В некотором роде браузер достаточно умен, чтобы разрешать ссылки.

=========================== Обновление - Использование решения Дэвида:

    'Regex to match all <a ... /a> links
    Dim myRegEx As New Regex("\<\s*a                   (?# Find opening <a tag)           " & _
                             ".+?href\s*=\s*['""]      (?# Then all to href=' or "" )     " & _
                             "(?<href>.*?)['""]        (?# Then all to the next ' or "" ) " & _
                             ".*?\>                    (?# Then all to > )                " & _
                             "(?<name>.*?)\<\s*/a\s*\> (?# Then all to </a> )             ", _
                             RegexOptions.IgnoreCase Or _
                             RegexOptions.IgnorePatternWhitespace Or _
                             RegexOptions.Multiline)

    'MatchCollection to hold all the links that are matched
    Dim myMatchCollection As MatchCollection
    myMatchCollection = myRegEx.Matches(Me._RawPageText)

    'Loop through all matches and evaluate the value of the href attribute.
    For i As Integer = 0 To myMatchCollection.Count - 1
        Dim thisLink As String = ""
        thisLink = myMatchCollection(i).Groups("href").Value()
        'This checks for Javascript and Mailto links.
        'This is not complete. There are others to check I just haven't encountered them yet.
        If thisLink.ToLower.StartsWith("javascript") Then
            thisLink = "JAVASCRIPT: " & thisLink
        ElseIf thisLink.ToLower.StartsWith("mailto") Then
            thisLink = "MAILTO: " & thisLink
        Else
            Dim baseUri As New Uri(Me.URL)

            If Not thisLink.ToLower.StartsWith("http") Then
                'This is a partial URL so we will assume that it's relative to our originating URL
                Dim myUri As New Uri(baseUri, thisLink)
                thisLink = "RELATIVE LOCAL LINK: RESOLVED: " & myUri.ToString() & " ORIGINAL: " & thisLink
            Else
                'The link starts with HTTP, determine if part of base host or is outside host.
                Dim ThisUri As New Uri(thisLink)
                If ThisUri.Host.ToLower = baseUri.Host.ToLower Then
                    thisLink = "INSIDE COMPLETE LINK: " & thisLink
                Else
                    thisLink = "OUTSIDE LINK: " & thisLink
                End If
            End If

        End If

        'I'm storing the found links into a Generic.List(Of String)
        'This link has descriptive text added to it.
        'TODO: Make collection to hold only unique internal links.
        Me._Links.Add(thisLink)
    Next

Ответы [ 3 ]

2 голосов
/ 06 мая 2009

Вы имеете в виду, как это?

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

1 голос
/ 06 мая 2009

Если вы имеете в виду серверную сторону, вы можете использовать ResolveUrl():

string url = ResolveUrl("~/questions");
0 голосов
/ 06 мая 2009

Я не понимаю, что вы подразумеваете под "разрешить" в этом контексте, но вы можете попробовать вставить базовый элемент HTML. Поскольку вы спросили, как браузер с этим справится.

"Тег <base> указывает адрес по умолчанию или цель по умолчанию для всех ссылок на странице."

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

...