urllib2提交http post请求

urllib2提交http post请求 - keep it simple, stupid - ITeye技术网站

urllib2实现是太强大,之前用c语言的curl库来实现post请求,觉着实太麻烦。

看了下urllib2的API文档,接着用它来模拟下xiami的登录,呵呵,就那么几行代码,简洁明了~

Python代码  收藏代码
  1. #!/usr/bin/python  
  2. #coding=utf-8  
  3.   
  4. import urllib  
  5. import urllib2  
  6.   
  7. def post(url, data):  
  8.     req = urllib2.Request(url)  
  9.     data = urllib.urlencode(data)  
  10.     #enable cookie  
  11.     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())  
  12.     response = opener.open(req, data)  
  13.     return response.read()  
  14.   
  15. def main():  
  16.     posturl = "http://www.xiami.com/member/login"  
  17.     data = {'email':'myemail''password':'mypass''autologin':'1''submit':'登 录''type':''}  
  18.     print post(posturl, data)  
  19.   
  20. if __name__ == '__main__':  
  21.     main()  
原文地址:https://www.cnblogs.com/lexus/p/2820179.html