Download a web page

From IronPython Cookbook

Using the WebClient class

A simple example:

from System.Net import WebClient
content = WebClient().DownloadString("")
print content

There are other useful shortcuts as well. For example, to download a 'page' (or resource) from the internet and save it as a file, you can use the WebClient.DownloadFile method:

from System.Net import WebClient
WebClient().DownloadFile(url, filename)

The longer way, that is more flexible if you want to configure the WebClient class, is:

from System.Net import WebClient
from System.IO import StreamReader

client = WebClient()
dataStream = client.OpenRead('')
reader = StreamReader(dataStream)
result = reader.ReadToEnd()
print result

Using the WebRequest and WebResponse classes

from System.Net import WebRequest
request = WebRequest.Create("")
response = request.GetResponse()
responseStream = response.GetResponseStream()
from System.IO import StreamReader
result = StreamReader(responseStream).ReadToEnd()
print result

For a convenience function, which works whether you are making a 'POST' or a 'GET', see Submit a POST form and download the result web page.

Back to Contents.