我有一个方法,返回的字符串格式如下:
string tableTag = "<th><a href="Boot_53.html">135 Boot</a></th>"
我想获取 href
属性的值并将其存储到另一个字符串中,称为 link
:
string link = "Boot_53.html"
换句话说,在字符串中应该将
link
赋予 href
属性。我该怎么做呢?我有一个方法,返回的字符串格式如下:
string tableTag = "<th><a href="Boot_53.html">135 Boot</a></th>"
我想获取 href
属性的值并将其存储到另一个字符串中,称为 link
:
string link = "Boot_53.html"
link
赋予 href
属性。我该怎么做呢?如果您知道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();
您可以使用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);
}
}
}
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);
}
HtmlAgilityPack
解析HTML:var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml( tableTag );
string link = doc.DocumentNode.SelectSingleNode("//a").Attributes["href"].Value;
你可以使用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"
}