概要
私は現在、このページにあるサイト用のパーサーを作成しようとしています。
私はすでにXPath(私はかなり得意です)を試しましたが、期待した結果を達成しようとして惨めに失敗したので、昨日から正規表現を使用しようとしています.
私の目標
ここでの私の目標は、この html をフラグメントに分割し、各フラグメントに 1 つのコースのデータを含めることです。
例:"AF - Bacharelado em Artes Visuais"
はコース名で、科目は まで青いテーブルで見つけることができます08º Semestre: 24 Créditos
。
その後"AG - Licenciatura em Artes - Artes Visuais"
、新しいコースの開始である などが表示されます。
このページには 2 つのコースしかありませんが、`このページには 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;
}
問題
コースの名前とそのオフセット (インデックス) に到達できるので、理論的には、Html を分割して、それぞれが 1 つのコースに関連するデータだけを含むようにすることができます。
ここに私がそれを試すために使用しているコードがあります。
- htmlPages は文字列のリストです
- auxHtml は、WebRequest によって取得された HtmlPage です。
コード
// 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);
}
理由はわかりませんが、インデックスがめちゃくちゃです。
2 番目のコース名のインデックスは 8022 ですが、試してみると、
auxHtml.Substring(0,8022)
次のコースの名前の前で終わる html の一部が表示されます。
ここで何が欠けていますか?
この「インデックス」属性は、HTML ページのパターンの開始のインデックスであるグループの「インデックス」属性ではありませんか?