0
    private void button1_Click(object sender, EventArgs e)
    {
        test();
    }


    public void test()
    {

        Dictionary<string, string> LnksDict = new Dictionary<string, string>();

        using (SmartWebClient smwc = new SmartWebClient())
        {

            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(smwc.DownloadString("http://www.google.com/adplanner/static/top1000/"));
            var links = htmlDoc.DocumentNode
                            .Descendants("a").Select(x => x.Attributes["href"]);
            foreach (var link in htmlDoc.DocumentNode.SelectNodes("//a"))
            {
                var UrlVal= link.Attributes["href"].Value;
                var name = UrlVal.Split('.')[1];

                LnksDict.Add(name, UrlVal);
            } 
        }
    }

#region <<=========== SmWbCl ============>>

public class SmartWebClient : WebClient
{
    private readonly int maxConcurentConnectionCount;

    public SmartWebClient(int maxConcurentConnectionCount = 20)
    {

        this.maxConcurentConnectionCount = maxConcurentConnectionCount;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var httpWebRequest = (HttpWebRequest)base.GetWebRequest(address);
        if (httpWebRequest == null)
        {
            return null;
        }

        if (maxConcurentConnectionCount != 0)
        {
            this.Proxy = null;
            this.Encoding = Encoding.GetEncoding("UTF-8");
            httpWebRequest.ServicePoint.ConnectionLimit = maxConcurentConnectionCount;
        }

        return httpWebRequest;
    }

}

#endregion

在这段代码中,我试图构建一个 url 列表,以便稍后用作自动完成源。

我做错的是将解析的值添加到字典中的条件。

我需要找到一种方法来添加域名作为密钥,即使已经存在,

所以我希望能够提出一个条件:

如果key此字典中的已经存在,则添加collection index当前linkstring.valuekey 作为后缀

或者,如果您想一起提出不同的解决方案......我很乐意看到新的例子。谢谢

4

1 回答 1

1

我认为你想要的,而不是 a Dictionary<string, string>,是 a Dictionary<string, HashSet<string>>。这样,您可以为每个域构建一个 URL 列表。您将项目添加到列表的代码将是:

var UrlVal= link.Attributes["href"].Value;
var name = UrlVal.Split('.')[1];

// get links for this host
HashSet hostLinksList;
if (!LnksDict.TryGetValue(name, out hostLinksList))
{
    hostLinksList = new HashSet<string>();
    LnksDict.Add(name, hostLinksList);
}
// add the URL to the list of links for this host
hostLinksList.Add(UrlVal);

这里的关键是当项目已经存在时调用AddaHashSet不会引发异常。它只是不再添加它并返回false以指示该项目已经在集合中。

完成后,您将获得每个主机(域)的 URL 列表,然后您可以将其用于自动完成。

顺便说一句,您使用拆分主机的方法Split('.')效果不佳。它采用“www.example.com”形式的域。例如,如果您遇到“example.com”(没有“www”),您将获得“com”作为名称。此外,“www.example.com”将与“www.example.org”和“www.example.co.uk”发生冲突。您需要一种更好的方法来识别主机。

于 2012-11-28T04:25:12.683 回答