【发布时间】:2023-04-02 02:10:01
【问题描述】:
尝试解析 HTML 文档并提取一些元素(任何指向文本文件的链接)。
当前的策略是将 HTML 文档加载到字符串中。然后找到文本文件链接的所有实例。它可以是任何文件类型,但对于这个问题,它是一个文本文件。
最终目标是拥有一个IEnumerable 字符串对象列表。这部分很简单,但解析数据是个问题。
<html>
<head><title>Blah</title>
</head>
<body>
<br/>
<div>Here is your first text file: <a href="http://myServer.com/blah.txt"></div>
<span>Here is your second text file: <a href="http://myServer.com/blarg2.txt"></span>
<div>Here is your third text file: <a href="http://myServer.com/bat.txt"></div>
<div>Here is your fourth text file: <a href="http://myServer.com/somefile.txt"></div>
<div>Thanks for visiting!</div>
</body>
</html>
最初的方法是:
- 将字符串加载到 XML 文档中,并以 Linq-To-Xml 方式对其进行攻击。
- 创建一个正则表达式,查找以
href=开头并以.txt结尾的字符串
问题是:
- 那个正则表达式会是什么样子?我是一个正则表达式新手,这是我学习正则表达式的一部分。
- 您会使用哪种方法来提取标签列表?
- 哪种方式最高效?
- 哪种方法可读性/可维护性最高?
更新: 感谢 Matthew 关于 HTML Agility Pack 的建议。它工作得很好! XPath 建议也适用。我希望我可以将两个答案都标记为“答案”,但我显然不能。它们都是解决问题的有效方法。
这是一个使用 Jeff 建议的正则表达式的 C# 控制台应用程序。它可以很好地读取字符串,并且不会包含任何不以 .txt 结尾的 href。对于给定的示例,它不会在结果中正确包含 .txt.snarg 文件(如 HTML 字符串函数中提供的那样)。
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace ParsePageLinks
{
class Program
{
static void Main(string[] args)
{
GetAllLinksFromStringByRegex();
}
static List<string> GetAllLinksFromStringByRegex()
{
string myHtmlString = BuildHtmlString();
string txtFileExp = "href=\"([^\\\"]*\\.txt)\"";
List<string> foundTextFiles = new List<string>();
MatchCollection textFileLinkMatches = Regex.Matches(myHtmlString, txtFileExp, RegexOptions.IgnoreCase);
foreach (Match m in textFileLinkMatches)
{
foundTextFiles.Add( m.Groups[1].ToString()); // this is your captured group
}
return files;
}
static string BuildHtmlString()
{
return new StringReader(@"<html><head><title>Blah</title></head><body><br/>
<div>Here is your first text file: <a href=""http://myServer.com/blah.txt""></div>
<span>Here is your second text file: <a href=""http://myServer.com/blarg2.txt""></span>
<div>Here is your third text file: <a href=""http://myServer.com/bat.txt.snarg""></div>
<div>Here is your fourth text file: <a href=""http://myServer.com/somefile.txt""></div>
<div>Thanks for visiting!</div></body></html>").ReadToEnd();
}
}
}
【问题讨论】:
-
您愿意使用开源 HTML 解析器吗?
-
@JD:绝对!正如 Matthew 所建议的,HTML Agility Pack 听起来值得一看。你会建议这个还是另一个?
-
@Philoushka 我本来打算推荐 HTML Agility Pack ......它太棒了。
标签: c# regex linq parsing linq-to-xml