如何在C#中从字符串中提取href标签?

8

我有一个方法,返回的字符串格式如下:

string tableTag = "<th><a href="Boot_53.html">135 Boot</a></th>"

我想获取 href 属性的值并将其存储到另一个字符串中,称为 link

string link = "Boot_53.html"

换句话说,在字符串中应该将 link 赋予 href 属性。我该怎么做呢?

“如何在C#中实现?”不是一个好的问题。请展示一下你已经尝试了什么,以及遇到了哪些难点。 - L.B
请看这个 Stack Overflow 的答案:https://dev59.com/yGUo5IYBdhLWcg3wmASi#15926523 - Colin Bacon
5个回答

13

如果您知道HTML实际上是XHTML(符合XML标准的HTML或多或少),则可以使用专门用于XML的工具轻松解析它(通常比用于HTML的工具更简单)。

var hrefLink = XElement.Parse("<th><a href=\"Boot_53.html\">135 Boot</a></th>")
                       .Descendants("a")
                       .Select(x => x.Attribute("href").Value)
                       .FirstOrDefault();

1
如果您正在使用带有a标签的文本,请将文本包装在<p>{text}</p>中,上述解决方案将起作用。 - College Code

12

您可以使用HTML解析器,例如HTML agility pack来解析输入的HTML并提取您需要的信息:

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        var doc = new HtmlDocument();
        string tableTag = "<th><a href=\"Boot_53.html\">135 Boot</a></th>";
        doc.LoadHtml(tableTag);

        var anchor = doc.DocumentNode.SelectSingleNode("//a");
        if (anchor != null)
        {
            string link = anchor.Attributes["href"].Value;
            Console.WriteLine(link);
        }
    }
}

9
您可以使用正则表达式:
string input= "<th><a href=\"Boot_53.html\">135 Boot</a></th>";
string regex= "href=\"(.*)\"";
Match match = Regex.Match(input, regex);
if (match.Success)
{
    string link= match.Groups[1].Value;
    Console.WriteLine(link);
}

3
使用 HtmlAgilityPack 解析HTML:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml( tableTag ); 
string link = doc.DocumentNode.SelectSingleNode("//a").Attributes["href"].Value;

0

你可以使用AngleSharp作为HtmlAgilityPack的替代品:

var context = BrowsingContext.New(Configuration.Default);

string tableTag = "<th><a href=\"Boot_53.html\">135 Boot</a></th>";

var document = await context.OpenAsync(req => req.Content(tableTag));

var anchor = document.All.FirstOrDefault(x => x.LocalName == "a");
if (anchor != null)
{
    string link = anchor.GetAttribute("href"); // "Boot_53.html"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接