Twisted系列-Hello world.

  使用一下twisted的getPage功能. 体会python语法特点.


代码:


  1. # -*- coding: utf-8 -*-
  2. from twisted.web.client import getPage
  3. from twisted.internet import reactor
  4. def printContents(contents):
  5.     
  6.     
  7.     print "获得内容:"
  8.     print contents.upper()
  9.     
  10.     reactor.stop()
  11.     
  12. def errorHandler(error):
  13.     print error
  14.     
  15.     reactor.stop()
  16. #请求
  17. deferred = getPage("http://localhost/test/Babel_s/yappr.php")
  18. #添加回调
  19. deferred.addCallback(printContents)
  20. deferred.addErrback(errorHandler)
  21. #反应堆~
  22. reactor.run()



说明:

1. python中, 注释一般是用 ''' 这种方式 ''' 的.

2. 没有{}来表示运行块, 用indent的深度来识别; 不适用分号来表示语句结束.

3. 指定encode的标记十分特别.

4. callback方式的.

5. Deferred对象来自于twisted.internet.defer.Deferred.

6.Python是case sensitive...



如果程序运行正常, 可以获得google首页所有的html代码.

你可能感兴趣的:(Twisted系列-Hello world.)