【发布时间】:2014-10-21 00:51:45
【问题描述】:
我有一个任务是在 C# 上编写一个程序,该程序可以找到网站上的所有 http 链接。现在我为它写了一个这样的函数:
async static void DownloadWebPage(string url)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
string[] resArr;
string result = await content.ReadAsStringAsync();
resArr = result.Split(new string[] {"href"}, StringSplitOptions.RemoveEmptyEntries);//splitting
//here must be some code-string which finds all neccessary http-links from resArr
Console.WriteLine("Main page of " + url + " size = " + result.Length.ToString());
}
}
使用这个函数,我将网页内容加载到字符串,然后我解析这个字符串并将结果写入数组,使用“href”-splitter,然后我检查字符串上的每个数组单元,其中包含“href” substring.So 我可以获得字符串,其中包含 http 链接。当字符串被拆分时问题就开始了,因为无法找到 http 链接,在我看来这是由于这个字符串的内容格式。如何解决它?
【问题讨论】:
-
您应该考虑使用实际的 Html 解析器,例如 HtmlAgilityPack。使用 string.Split(或正则表达式)是个坏主意。
-
你没有解析任何东西。
<a href="#"></a>将导致<a和="#"></a>。如果你添加更多的链接,你会有更多的垃圾。您必须为此使用 HTML 解析器(并且它不会考虑从 JavaScript 触发的链接)。一个原始的解决方案可能是使用正则表达式(请注意,您将匹配 URL,您不能使用正则表达式来解析 HTML)来查找所有 URL,但是您必须清理该列表(例如删除 POST、脚本、CSS等等)。
标签: c# httpclient httpcontent