python httplib post 进行表单提交数据

Ubuntu每日小技巧:

Python的模块  httplib 利用post进行表单数据提交.{用以实现自动发布这个功能,前提是不需要登录的情况;登录的情况还需要研究,暂时没搞定呢}

学习知识点:

  httplib request的用法
  getresponse() 用以进行返回数据

看下面的列子:

Python代码
  1. #!/usr/bin/python  
  2. #-*-coding:utf-8-*-  
  3.   
  4. # 进行表单提交  小项  2008-10-09  
  5.   
  6. import httplib,urllib;  #加载模块  
  7.   
  8. #定义需要进行发送的数据  
  9. params = urllib.urlencode({'cat_id':'6',  
  10.                            'news_title':'标题-Test39875',  
  11.                            'news_author':'Mobedu',  
  12.                            'news_ahome':'来源',  
  13.                            'tjuser':'carchanging',  
  14.                            'news_keyword':'|',  
  15.                            'news_content':'测试-Content',  
  16.                            'action':'newnew',  
  17.                            'MM_insert':'true'});  
  18. #定义一些文件头  
  19. headers = {"Content-Type":"application/x-www-form-urlencoded",  
  20.            "Connection":"Keep-Alive","Referer":"http://192.168.1.212/newsadd.asp?action=newnew"};  
  21. #与网站构建一个连接  
  22. conn = httplib.HTTPConnection("192.168.1.212");  
  23. #开始进行数据提交   同时也可以使用get进行  
  24. conn.request(method="POST",url="/newsadd.asp?action=newnew",body=params,headers=headers);  
  25. #返回处理后的数据  
  26. response = conn.getresponse();  
  27. #判断是否提交成功  
  28. if response.status == 302:  
  29.     print "发布成功!^_^!";  
  30. else:  
  31.     print "发布失败\^0^/";  
  32. #关闭连接  
  33. conn.close();  

 

Tags: 表单提交, python代码, httplib, post数据

1条记录访客评论

缺点是没有timeout

Post by ruf on 2008, October 28, 6:40 AM 引用此文发表评论 #1


发表评论

评论内容 (必填):