代码之家  ›  专栏  ›  技术社区  ›  Sheff

使用Regex从html链接中获取“标题”属性

  •  0
  • Sheff  · 技术社区  · 17 年前

    <a\s+((?:(?:\w+\s*=\s*)(?:\w+|"[^"]*"|'[^']*'))*?\s*href\s*=\s*(?<url>\w+|"[^"]*"|'[^']*')(?:(?:\s+\w+\s*=\s*)(?:\w+|"[^"]*"|'[^']*'))*?)>.+?</a>
    

    • 链接的标题属性

    然后,我可以检查每个子组的匹配情况,以获取链接的相关名称。

    3 回复  |  直到 17 年前
        2
  •  2
  •   Goyuix    17 年前

    Regex reg = new Regex("<a[^>]*?title=\"([^\"]*?\"[^>]*?>");
    

    几个陷阱:

    reg.Match("<a href=\"#\" title=\"Hello\">Howdy</a>").Groups[1].Value
    
        3
  •  0
  •   Sheff    17 年前

    感谢混沌。Owens向我推荐了HtmlAgilityPack库,这很棒。最后,我用它来解决我的问题,如下所示。 我强烈推荐这个图书馆给其他人。

       HtmlDocument htmldoc = new HtmlDocument();
        htmldoc.LoadHtml(content);
        HtmlNodeCollection linkNodes = htmldoc.DocumentNode.SelectNodes("//a[@href]");
        if (linkNodes != null)
        {
            foreach (HtmlNode linkNode in linkNodes)
            {
                string linkTitle = linkNode.GetAttributeValue("title", string.Empty);
                //If no title attribute exists check for an image alt tag
                if (linkTitle == string.Empty)
                {
                    HtmlNode imageNode = linkNode.SelectSingleNode("img[@alt]");
                    if (imageNode != null)
                    {
                        linkTitle = imageNode.GetAttributeValue("alt", string.Empty);
                    }
                }
                //If no image alt tag check for span with text
                if (linkTitle == string.Empty)
                {
                    HtmlNode spanNode = linkNode.SelectSingleNode("span");
                    if (spanNode != null)
                    {
                        linkTitle = spanNode.InnerText;
                    }
                }
    
                if (linkTitle == string.Empty)
                {
                    if (!linkNode.HasChildNodes)
                    {
                        linkTitle = linkNode.InnerText;
                    }
                }
    
            }
        }
    
    推荐文章