从html锚标记C#中获取href值

时间:2012-08-23 08:11:59

标签: asp.net c#-4.0

如何使用C#从html锚标记获取href值 谢谢

string ref="<a href="http://www.google.com"></a>";
//i want get result from 
//string ref like 
//http://www.google.com

4 个答案:

答案 0 :(得分:3)

您可以使用HTML解析库,例如Html Agility Pack。例如:

using System;
using HtmlAgilityPack;

class Program
{
    static void Main()
    {
        var doc = new HtmlDocument();
        doc.LoadHtml("<a href=\"http://www.google.com\"></a>");
        var nodes = doc.DocumentNode.SelectNodes("a[@href]");
        foreach (var node in nodes)
        {
            Console.WriteLine(node.Attributes["href"].Value);
        }
    }
}

答案 1 :(得分:3)

如果您想在没有 HtmlAgilityPack 的情况下执行此操作,则可以使用正则表达式执行此操作:

 string ref= @"<a href=""http://www.google.com"">test</a>";
 var regex = new Regex("<a [^>]*href=(?:'(?<href>.*?)')|(?:\"(?<href>.*?)\")", RegexOptions.IgnoreCase);
 var urls = regex.Matches(ref).OfType<Match>().Select(m => m.Groups["href"].Value).SingleOrDefault();

希望它对你有所帮助。

答案 2 :(得分:1)

使用htmlagilitypack

    var url= @"<a href="http://stackoverflow.com" ></a>";
    HtmlDocument document = new HtmlDocument();
    document.LoadHtml(url);
    var tempValue= document.DocumentNode.SelectSingleNode("//a");
    var link= tempValue.Attributes["href"].Value;

答案 3 :(得分:0)

如果您需要锚链接以及锚文本,则可以使用下面的函数,该函数返回包含HTML字符串中所有锚(URL;文本)的字符串列表。

 public static List<string> ExtractLinks(string htmlString)
    {
        List<string> list = new List<string>();
        string anchorStart = "<a";
        string anchorEnd = "</a>";
        string anchorText = string.Empty;
        Regex regex = new Regex("(?:href)=[\"|']?(.*?)[\"|'|>]+", RegexOptions.Singleline | RegexOptions.CultureInvariant);
        if (regex.IsMatch(htmlString))
        {
            foreach (Match match in regex.Matches(htmlString))
            {
                try
                {
                    string strURL = match.Groups[1].Value; // should contain the HRF URL 

                    int baseIndex = htmlString.IndexOf(strURL); // Get the Start Index of current URL.                       

                    // Start from baseindex and finc the fisrt instance of "<a" which should be the start of anchor
                    int anchorStartIndex = htmlString.LastIndexOf(anchorStart, baseIndex, StringComparison.CurrentCultureIgnoreCase);

                    // Find the end index of anchor 
                    int anchorEndIndex = htmlString.IndexOf(anchorEnd, anchorStartIndex, StringComparison.CurrentCultureIgnoreCase);

                    // The actual anchor text would be found b/w ">"  and "</a>" so need to find the index of ">"
                    int indexofanchorTextStart = htmlString.LastIndexOf(">", anchorEndIndex);

                    //find the substring b/w ">" and "</a>"
                    anchorText = htmlString.Substring(indexofanchorTextStart + 1, anchorEndIndex - indexofanchorTextStart - 1);
                    anchorText = HttpUtility.HtmlDecode(anchorText);

                    // get Full anchor from start to end
                    // string substringAheadAnchor = htmlString.Substring(anchorStartIndex, anchorEndIndex - anchorStartIndex + anchorEnd.Length + 1);

                }
                catch (Exception ex)
                {
                    // Log Exception in parsing the anchor Text 
                }

                if (!list.Contains(match.Groups[1].Value + ";" + anchorText))
                {
                    list.Add(match.Groups[1].Value + ";" + anchorText);// Append URL and Text using semicolun as seperator.  
                }
            }
        }

        return list;
    }