1

我有一个任务是在 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”子字符串。所以我可以获得字符串,其中包含 http 链接。问题开始于字符串拆分时,因为无法找到 http 链接,在我看来这是由于该字符串的内容格式。如何解决?

4

1 回答 1

0

我曾经做过类似的事情。我的解决方案是以符合 xml 规则的方式更改 html。(这可能是这个解决方案的问题,我相信我的 html 在某种程度上是预定义的,所以我只需要更改一些我知道在 html 中不符合 xml 的东西)

在此之后,您可以简单地搜索“a”节点并阅读 href 参数。

不幸的是,我再也找不到我的代码了,太久了。

于 2014-08-27T12:41:12.153 回答