【发布时间】:2010-01-31 23:37:58
【问题描述】:
我从以下 URL csharp-online 中的示例中获得灵感 并打算从此页面检索所有 URL alexa
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
namespace ExtractingUrls
{
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
const string url = "http://www.alexa.com/topsites/category/Top/Society/History/By_Topic/Science/Engineering_and_Technology";
string source = client.DownloadString(url);
//Console.WriteLine(Getvals(source));
string matchPattern =
@"<a.rel=""nofollow"".style=""font-size:0.8em;"".href=[""'](?<url>[^""^']+[.]*)[""'].class=""offsite"".*>(?<name>[^<]+[.]*)</a>";
foreach (Hashtable grouping in ExtractGroupings(source, matchPattern, true))
{
foreach (DictionaryEntry DE in grouping)
{
Console.WriteLine("Value = " + DE.Value);
Console.WriteLine("");
}
}
// End.
Console.ReadLine();
}
public static ArrayList ExtractGroupings(string source, string matchPattern, bool wantInitialMatch)
{
ArrayList keyedMatches = new ArrayList();
int startingElement = 1;
if (wantInitialMatch)
{
startingElement = 0;
}
Regex RE = new Regex(matchPattern, RegexOptions.Multiline);
MatchCollection theMatches = RE.Matches(source);
foreach (Match m in theMatches)
{
Hashtable groupings = new Hashtable();
for (int counter = startingElement; counter < m.Groups.Count; counter++)
{
// If we had just returned the MatchCollection directly, the
// GroupNameFromNumber method would not be available to use
groupings.Add(RE.GroupNameFromNumber(counter),
m.Groups[counter]);
}
keyedMatches.Add(groupings);
}
return (keyedMatches);
}
}
}
但是在这里我遇到了一个问题,当我执行每个 URL 时会显示三次,首先是显示整个锚标记,然后是显示两次 URL。谁能建议我应该在哪里更正,以便我可以让每个 URL 只显示一次。
【问题讨论】:
-
不要不使用正则表达式解析 HTML! stackoverflow.com/questions/1732348/…
-
@SLacks: "解析有限的已知 HTML 集有时是合适的"