Tuesday, 26 April 2011

How To Download A Web Page Using F#

The following code example shows you how to download an entire web page using F#. Keep in mind that the data you receive from this code will be the raw html as well as the actual data you want, so you will have to write your own code to sift through it all.




open System
open System.IO
open System.Net


//Create A Variable To Hold The Page Url
let pageToLoad = "http://www.google.com"




//A Simple Try Catch Block TO Allow Our App To Fail GraceFully On Error
try
//Create A WebRequest Object And Pass It The Variable Holding The Page Url
let request = WebRequest.Create(pageToLoad)
//Create A WebResponse Object
let Response = request.GetResponse()
//Create A StreamReader Object
let sr = new StreamReader(Response.GetResponseStream())
//Download The Entire Page Into A Variable Called page
let page = sr.ReadToEnd()
//Display The Page Data To The User
Console.WriteLine(page)
//Wait For The User To Press A Key Before Closing The Console
Console.ReadKey()
finally
//If We Get Here There Has Been An Error. Check Your Internet Connection'
Console.WriteLine("There was an error, press a key to quit!")
Console.ReadKey()
        

No comments:

Post a Comment