Chinaunix首页 | 论坛 | 博客
  • 博客访问: 536496
  • 博文数量: 142
  • 博客积分: 2966
  • 博客等级: 少校
  • 技术积分: 1477
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-07 22:37
文章分类

全部博文(142)

文章存档

2013年(3)

2012年(21)

2011年(53)

2010年(33)

2009年(32)

分类: Python/Ruby

2011-05-05 11:23:36

 

  1. 在使用urllib的时候经常会死掉,以前debug过,是没有设置 timing out 所以超时后就会死掉。
  2. PycURL是curl的python库,虽然有些curl的功能没有实现,但是还是很强劲的。


  3. curl是非常强劲的一个工具,
  4. google内部用它来 debug GDATA API. Using cURL to interact with Google data services


  5. 可以去 http://pycurl.sourceforge.net/ 下载最新的PycURL。

  6. 简单的PycURL例子

  7. import pycurl
  8. import StringIO

  9. url = ""
  10. crl = pycurl.Curl()
  11. crl.setopt(pycurl.VERBOSE,1)
  12. crl.setopt(pycurl.FOLLOWLOCATION, 1)
  13. crl.setopt(pycurl.MAXREDIRS, 5)
  14. crl.fp = StringIO.StringIO()
  15. crl.setopt(pycurl.URL, url)
  16. crl.setopt(crl.WRITEFUNCTION, crl.fp.write)
  17. crl.perform()
  18. print crl.fp.getvalue()
  19. PycURL 自动处理cookie
  20. import pycurl
  21. import StringIO

  22. url = ""
  23. crl = pycurl.Curl()
  24. crl.setopt(pycurl.VERBOSE,1)
  25. crl.setopt(pycurl.FOLLOWLOCATION, 1)
  26. crl.setopt(pycurl.MAXREDIRS, 5)
  27. crl.fp = StringIO.StringIO()
  28. crl.setopt(pycurl.URL, url)
  29. crl.setopt(crl.WRITEFUNCTION, crl.fp.write)

  30. # Option -b/--cookie <name=string/file> Cookie string or file to read cookies from
  31. # Note: must be a string, not a file object.
  32. crl.setopt(pycurl.COOKIEFILE, "cookie_file_name")

  33. # Option -c/--cookie-jar <file> Write cookies to this file after operation
  34. # Note: must be a string, not a file object.
  35. crl.setopt(pycurl.COOKIEJAR, "cookie_file_name")

  36. crl.perform()
  37. print crl.fp.getvalue()

 

  1. PycURL 实现POST方法
  2. import pycurl
  3. import StringIO
  4. import urllib

  5. url = ""
  6. post_data_dic = {"name":"value"}
  7. crl = pycurl.Curl()
  8. crl.setopt(pycurl.VERBOSE,1)
  9. crl.setopt(pycurl.FOLLOWLOCATION, 1)
  10. crl.setopt(pycurl.MAXREDIRS, 5)
  11. #crl.setopt(pycurl.AUTOREFERER,1)

  12. crl.setopt(pycurl.CONNECTTIMEOUT, 60)
  13. crl.setopt(pycurl.TIMEOUT, 300)
  14. #crl.setopt(pycurl.PROXY,proxy)
  15. crl.setopt(pycurl.HTTPPROXYTUNNEL,1)
  16. #crl.setopt(pycurl.NOSIGNAL, 1)
  17. crl.fp = StringIO.StringIO()
  18. crl.setopt(pycurl.USERAGENT, "dhgu hoho")

  19. # Option -d/--data <data> HTTP POST data
  20. crl.setopt(crl.POSTFIELDS, urllib.urlencode(post_data_dic))

  21. crl.setopt(pycurl.URL, url)
  22. crl.setopt(crl.WRITEFUNCTION, crl.fp.write)
  23. crl.perform()

  24. print crl.fp.getvalue()
  25. urllib 超时设置
  26. import socket
  27. socket.setdefaulttimeout(5.0)
阅读(2292) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~