Saturday, March 14, 2009

python发送post保存cookie封装

近期刚写完某SNS的一个刷人气机器人(仅仅做技术测试),然后封装了这个功能。

socket = Httpsocket()
创建一个请求实例,并初始化 cookie容器

socket.connect(url,param)
请求处理post的url和post 参数 执行完后 会返回该socket

socket.openurl(url)
通过持有上一步中得到的cookie来访问接下来的网络地址。


# auther: free.Wang<freefis@gmail.com>

import urllib
import urllib2

class Httpsocket:
 """ Build for Make a full HttpRequest via POST/GET """
 def __init__(self):
# login url to recieve param , Post/Get param
# opener will be used to open Url with cookie.
# build the cookie container.
  self.cookies = urllib2.HTTPCookieProcessor()
  self.opener = urllib2.build_opener(self.cookies)
  urllib2.install_opener(self.opener)

 def connect(self,loginurl,param):
 """make a Container for Cookie"""
  self.loginurl = loginurl
  self.param = param
  self.encodeparam = urllib.urlencode(self.param)
  try:
   urllib2.urlopen(urllib2.Request(self.loginurl,self.encodeparam))
  except:
   pass

 def openurl(self,url):
 """ get Response. """
# serialize the Param
# Login to Get Cookie ,Which will be Push into self.opener.
# get request with Cookie.
  return self.opener.open(url)

No comments:

Followers