尝试解析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建议也有效。我希望我能将两个答案都标记为“答案”,但我显然不能。它们都是解决问题的有效方法。
这是一个C#控制台应用程序,使用Jeff建议的正则表达式。它可以正确读取字符串,并且不会包含任何没有以.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();
}
}
}