我下載了一個帶有WebClient和downloadString()的html站點,然後我嘗試將它們之間的所有鏈接都放到一個列表中。
經過幾次嘗試和兩個小時的工作,有一次我得到了所有的鏈接,有時候我只得到一個,有時我得不到。
這是我的代碼示例 - 我只是讓Catch Block離開以獲得更好的可讀性。
List<string> getLinks = new List<string>();
for (int i = 0; i < wikiUrls.Length; i++)
{
try
{
string download = client.DownloadString(wikiUrls[i]);
string searchForDiv = "<div class=\"wiki\">";
int firstCharacter = download.IndexOf(searchForDiv);
//if wiki doens't exists, go to next element of for loop
if (firstCharacter == -1)
continue;
else
{
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(download);
string nodes = String.Empty;
var div = document.DocumentNode.SelectSingleNode("//div[@class=\"wiki\"]");
if (div != null)
{
getLinks = div.Descendants("a").Select(node => node.GetAttributeValue("href", "Not found \n")).ToList();
output.Text = string.Join(" ", getLinks);
}
}
}
我知道了。這是因為
getLinks = div.Descendants("a").Select(node => node.GetAttributeValue("href", "Not found \n")).ToList();
GetLinks總是被覆蓋,因為它處於for循環中。我解決了這個問題:
getLinks.AddRange(div.Descendants("a").Select(node => node.GetAttributeValue("href", String.Empty)).ToList());