概观
我目前正在尝试为该页面中的网站编写解析器.
我已经尝试过XPath(我很擅长)并且我很难勉强尝试达到预期的结果,所以我从昨天开始尝试使用正则表达式.
我的目标
我的目标是将这个html分成片段,每个片段包含单个课程的数据.
例如:"AF - Bacharelado em Artes Visuais"是课程名称,主题可以在蓝色表格中找到,直到08º Semestre: 24 Créditos.
之后,您可以看到"AG - Licenciatura em Artes - Artes Visuais",这是新课程的开始,依此类推.
这个页面只有两个课程,但是这个课程可以有2个以上.
正则表达式问题
我的一个朋友给了我一只手,发现使用这种模式和选项,可以达到课程的名称.这是一些代码:
// Creating Regular Expression to find name of courses
Regex regex = new Regex ("<p><br><b><font face=\"Arial,Helvetica\"><font color=\"#000099\"><font size=-1>(.+?)</font></font></font></b>", RegexOptions.Singleline);
int startIndex = 0;
while (regex.IsMatch (auxHtml, startIndex))
{
// Checking name of the course and saving it's offset
int index = regex.Match(auxHtml, startIndex).Groups[1].Index;
string courseName = regex.Match(auxHtml, startIndex).Groups[1].Value;
}
Run Code Online (Sandbox Code Playgroud)
问题
因为我可以达到一个课程的名称和它的偏移(索引),理论上,我可能能够将Html分成几个部分,其中每个部分只包含与单个课程相关的数据.
这是我用来尝试它的代码.
码
// Creating Regular Expression to find name of courses
Regex regex = new Regex ("<p><br><b><font face=\"Arial,Helvetica\"><font color=\"#000099\"><font size=-1>(.+?)</font></font></font></b>", RegexOptions.Singleline);
int startIndex = 0;
while (regex.IsMatch (auxHtml, startIndex))
{
// Checking name of the course and saving it's offset
int index = regex.Match(auxHtml, startIndex).Groups[1].Index;
string courseName = regex.Match(auxHtml, startIndex).Groups[1].Value;
// Adding name of the course and offset to dictionary
courseIndex.Add (courseName,index);
startIndex = regex.Match(auxHtml, startIndex).Groups[1].Index;
// Splitting HTML Page
if (regex.IsMatch(auxHtml, startIndex))
{
int endIndex = regex.Match (auxHtml, startIndex).Groups[1].Index;
endIndex = endIndex - startIndex;
htmlPiece = auxHtml.Remove(startIndex, endIndex);
}
htmlPages.Add(auxHtml);
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么,但索引有点混乱.
第二个课程名称的索引是8022,但是,如果我尝试:
auxHtml.Substring(0,8022)
Run Code Online (Sandbox Code Playgroud)
它给了我一个html的一部分,它在下一个课程的名称之前结束.
我在这里错过了什么?
是不是这个组的"索引"属性,是html页面中模式开始的索引?
虽然您可能几乎可以使用RegEx实现您正在寻找的东西,但它一定很难.
正则表达式不适合这项工作.使用XML解析器解析HTML会更好.这是因为HTML(和一般的XML)标记不是常规语言 - 因此正则表达式在这种情况下不是很有用.
您应该查看System.Xml.XmlDocument类.