如何使用C#从谷歌搜索获得前N个结果?

时间:2016-03-16 21:18:05

标签: c# html-agility-pack google-search google-custom-search google-search-api

如何使用c#从谷歌搜索获得前N个结果?

using (var webclient = new WebClient())
        {
            const string url = "https://www.google.com.au/search?num=100&q=my+search+term";
            var  result = webclient.DownloadString(url);
        }

更新

如何获取特定网址出现的位置和次数?

1 个答案:

答案 0 :(得分:2)

以下将返回搜索“我的搜索字词”的前100个结果,并返回指定目标“mytarget”的顺序

internal class Program
{
    private const string Url = "http://www.google.com/search?num=100&q=my+search+term";

    private static void Main(string[] args)
    {
        var result = new HtmlWeb().Load(Url);
        var nodes = result.DocumentNode.SelectNodes("//html//body//div[@class='g']");
        var indexes = nodes == null
                          ? new List<int> { 0 }
                          : nodes.Select((x, i) => new { i, x.InnerHtml })
                                .Where(x => x.InnerHtml.Contains("mytarget"))
                                .Select(x => x.i + 1)
                                .ToList();


        Console.WriteLine(String.Join(", ", indexes));
        Console.ReadLine();
    }
}

使用正则表达式执行此操作的另一种方法:

 string html;
        using (var webClient = new WebClient())
        {
            html = webClient.DownloadString(searchUrl);
        }

        var regex = new Regex("<div class=\"g\">(.*?)</div>");

        var matches = regex.Matches(html).Cast<Match>().ToList();

        var indexes = matches.Select((x, i) => new { i, x })
            .Where(x => x.ToString().Contains("mytarget"))
            .Select(x => x.i + 1)
            .ToList();