如何从我的游戏中搜索谷歌

时间:2017-06-12 08:49:20

标签: c# unity3d

我正在尝试在游戏中使用谷歌搜索。我想找出特定搜索查询返回的结果数。

目前,我正在使用搜索查询打开网址。然而谷歌的工作方式是加载页面然后在搜索结果中流式传输。 Unity认为页面已完全加载,然后很快就会返回结果。

以下是我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;

public class SearchWeb: MonoBehaviour {

  // I call this method to start the search from an input field
  public void Search(InputField _inputField) {
    StartCoroutine(GetHtml(_inputField.text.ToString(), ShowResults));
  }

  // This is my callBack that will post results in the console
  public void ShowResults(int _results, string _searchQuery) {
    Debug.Log("searching for " + _searchQuery + " results in " + _results + " results.");
  }

  // This method is responsible for recieving the HTML from a search query
  // 
  IEnumerator GetHtml(string _searchQuery, Action < int, string > _callback) {
    // White space in the a google search will return an error from google
    _searchQuery = _searchQuery.Replace(" ", "+");
    // The URL to send
    string url = "https://www.google.com/search?sclient=psy-ab&btnG=Search&q=" + _searchQuery.ToString();
    WWW wwwHTML = new WWW(url);
    Debug.Log("Attempting to search " + url);
    yield
    return wwwHTML;
    // Process the returned HTML, get useful information out of it
    int _results = GetResults(wwwHTML.text.ToString());
    // Send it back
    _callback(_results, _searchQuery);
    yield
    return null;
  }

  // This method is incomplete but would eventually return the number of results my search query found
  private int GetResults(string _html) {
    Debug.Log(_html);
    // Here I can tell by looking in the console if the returned html includes the search results
    // At the moment it doesn't

    int _startIndex = 0;
    int _results = 0;

    // looking for this <div id="resultStats"> where the search results are placed
    if (_html.IndexOf("<div id=\"resultStats\">", System.StringComparison.Ordinal) > 0) {
      _startIndex = _html.IndexOf("<div id=\"resultStats\">", System.StringComparison.Ordinal);
      // TODO - Finish this stuff
    }
    // TODO - For now I'm just debugging to see if I've found where the result stats may be
    _results = _startIndex;
    return _results;
  }
}

它目前返回不包含任何搜索结果的html

2 个答案:

答案 0 :(得分:4)

我不认为Google会像您一样以这种方式使用他们的服务 - 他们非常希望您通过Custom Search API注册并访问这些内容。这是一个很好的基于JSON的api,因此您可以避免进行任何HTML处理。从Unity中的JSON响应中获取答案应该非常简单。

答案 1 :(得分:1)

原创教程here。只需使用 GoogleSearch.Search()功能即可。可以找到Github上的源代码项目here

string query = "The University of Hong Kong";
var results = GoogleSearch.Search(query);
foreach (Result result in results)
{
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("Title: {0}", result.Title);
    Console.WriteLine("Link: {0}", result.Link);
}
Console.ReadKey();