我有以下代码,但是,当我启动它时,我只接缝以返回一些URL。
while (stopFlag != true)
{
WebRequest request = WebRequest.Create(urlList[i]);
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader
(response.GetResponseStream(), Encoding.UTF8))
{
string sitecontent = reader.ReadToEnd();
//add links to the list
// process the content
//clear the text box ready for the HTML code
//Regex urlRx = new Regex(@"((https?|ftp|file)\://|www.)[A-Za-z0-9\.\-]+(/[A-Za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*", RegexOptions.IgnoreCase);
Regex urlRx = new Regex(@"(?<url>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);
MatchCollection matches = urlRx.Matches(sitecontent);
foreach (Match match in matches)
{
string cleanMatch = cleanUP(match.Value);
urlList.Add(cleanMatch);
updateResults(theResults, "\"" + cleanMatch + "\",\n");
}
}
}
}
我认为错误在正则表达式中。
我想要实现的是拉一个网页,然后从该页面获取所有链接 - 将这些链接添加到列表中,然后为每个列表项获取下一页并重复该过程。
答案 0 :(得分:3)
我建议使用一个好的HTML解析器,而不是尝试使用regex to parse HTML,HTML Agilty Pack是一个很好的选择:
什么是Html Agility Pack(HAP)?
这是一个敏捷的HTML解析器,它构建一个读/写DOM并支持普通的XPATH或XSLT(你实际上不需要理解XPATH或XSLT来使用它,不用担心......)。它是一个.NET代码库,允许您解析“out of the web”HTML文件。解析器非常容忍“真实世界”格式错误的HTML。对象模型与提出System.Xml非常相似,但对于HTML文档(或流)。