0

我有一个问题......我会创建一个应用程序来抓取谷歌搜索的结果......但是当我尝试使用 downloadstringasync 时,调试返回一个错误“无法将'void'分配给局部变量...... "

你说我怎么解决?

这是代码

        public class SearchResult
    {
        public string url;
        public string title;
        public string content;
        public FindingEngine engine;

        public enum FindingEngine { google, bing, google_and_bing };

        public SearchResult(string url, string title, string content, FindingEngine engine)
        {
            this.url = url;
            this.title = title;
            this.content = content;
            this.engine = engine;
        }
    }

public static List<SearchResult> GoogleSearch(string search_expression, 
  Dictionary<string, object> stats_dict)
{
  var url_template = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q={0}&start={1}";
  Uri search_url;
  var results_list = new List<SearchResult>();
  int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
  foreach (var offset in offsets)
  {

    var searchUrl = new Uri(string.Format(url_template, search_expression, offset));
    var page = new WebClient().DownloadStringAsync(searchUrl);
    var o = (JObject)JsonConvert.DeserializeObject(page);

    var results_query =
      from result in o["responseData"]["results"].Children()
      select new SearchResult(
          url: result.Value<string>("url").ToString(),
          title: result.Value<string>("title").ToString(),
          content: result.Value<string>("content").ToString(),
          engine: SearchResult.FindingEngine.google
          );

    foreach (var result in results_query)
      results_list.Add(result);
  }

  return results_list;
}

谢谢!

4

1 回答 1

1

DownloadStringAsync不返回任何东西,即 avoid所以你不能简单地为它分配一个变量。

您需要添加一个事件处理程序,完成DownloadStringCompleted后将触发该事件处理程序DownloadStringAsync

var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(searchUrl);

static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
  // e.Result will contain the returned JSON. Move the code that parse the result to here.
}
于 2013-06-02T13:03:29.817 回答