浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Download a web page - IronPython Cookbook

Download a web page

From IronPython Cookbook

Using the WebClient class

A simple example:

from System.Net import WebClient
content = WebClient().DownloadString("http://google.com")
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('http://google.com')
reader = StreamReader(dataStream)
result = reader.ReadToEnd()
print result

Using the WebRequest and WebResponse classes

from System.Net import WebRequest
request = WebRequest.Create("http://google.com")
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.

posted on 2012-12-13 15:35  lexus  阅读(223)  评论(0编辑  收藏  举报