Hello, I want to download a html using Unity Webrequest and retrieve the data (its actually google). I want to do this because I want to retrieve the count of results from google search. But when I dwonlload the file, tthe results are just missing. I wrote two different codes but both of them are not working. Heres the first:
public class SearchGoogle : MonoBehaviour
{
public string keyword;
private string searchwebsite;
string fileName = "MyFile.html";
string html;
void Start()
{
searchwebsite = "https://www.google.com/search?q=" + keyword;
Debug.Log(searchwebsite);
StartCoroutine(GetText());
Debug.Log("Coroutine gets callt");
}
IEnumerator GetText()
{
UnityWebRequest www = UnityWebRequest.Get(searchwebsite);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("Error: ");
Debug.Log(www.error);
}
else
{
html = www.downloadHandler.text;
checkfor();
//filecreation
var sr = File.CreateText(fileName);
sr.WriteLine(www.downloadHandler.text);
sr.Close();
}
}
void checkfor()
{
string input = html;
string search = "
";
int p = input.IndexOf(search);
if (p >= 0)
{
// move forward to the value
int start = p + search.Length;
// now find the end by searching for the next closing tag starting at the start position,
// limiting the forward search to the max value length
int end = input.IndexOf("
", start);
if (end >= 0)
{
// pull out the substring
string v = input.Substring(start, end - start);
Debug.Log(v);
// finally parse into a float
float value = float.Parse(v);
Debug.Log("Value = " + value);
}
else
{
Debug.Log("Bad html - closing tag not found");
}
}
else
{
Debug.Log("result-stats div not found");
}
}
}
The second is this:
public class test : MonoBehaviour
{
public string keyword;
private string link;
void Start()
{
link = "http://google.com/search?q=" + keyword;
StartCoroutine(DownloadFile());
}
IEnumerator DownloadFile()
{
var uwr = new UnityWebRequest(link, UnityWebRequest.kHttpVerbGET);
string path = Path.Combine(Application.persistentDataPath, "unity3d.html");
uwr.downloadHandler = new DownloadHandlerFile(path);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
Debug.LogError(uwr.error);
else
Debug.Log("File successfully downloaded and saved to " + path);
}
}
I would really apreciate if someone could tell me why, none could tell me over at stack.