In questi due esempi sono stati utilizzati linguaggio c#, la classe WebClient e la classe HttpWebRequest.
Nel primo esempio la classe WebClient con un semplice metodo ricerca il codice html a partire da un Url.
Nel secondo esempio ho creato un metodo e ho utilizzato la classe HttpWebRequest per la ricerca del codice html sempre a partire da un url/sito utilizzando un user agent di un browser.
Questo secondo esempio è stato creato perchè a volte alcuni siti inibiscono l'accesso e quindi la "cattura" del codice se si proviene con degli applicativi software o "Robot", ma lasciano entrare solamente "visitatori umani".
Viene in aiuto la classe HttpWebRequest con il parametro UserAgent da settare cosicchè l'applicativo potrà "diventare" un "visitatore umano" per questi tipi di siti.
Ma a volte la "cattura" del codice può impiegare più di un tempo previsto standard, per cui si dovranno impostare i vari timeout di risposta.
1 esempio:
string htmlCode=""; string strUrlNew = "http://www.example.com"; using (WebClient client = new WebClient()) { htmlCode = client.DownloadString(strUrlNew); }
2 esempio:
private string DownloadContentSite(string url) { string htmlCode = ""; Byte[] bytes; Uri absoluteUri = new Uri(url.Trim()); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(absoluteUri); webRequest.Method = "GET"; webRequest.AllowAutoRedirect = false; webRequest.Timeout = 60000; webRequest.ReadWriteTimeout = 60000; webRequest.Accept = "*/*"; webRequest.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)"; using (WebResponse webResponse = webRequest.GetResponse()) { string contentType = webResponse.ContentType; using (Stream stream = webResponse.GetResponseStream()) { using (MemoryStream memoryStream = new MemoryStream()) { Byte[] buffer = new Byte[0x1000]; Int32 bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, bytesRead); } bytes = memoryStream.ToArray(); } } } htmlCode = System.Text.Encoding.UTF8.GetString(bytes); return htmlCode; }