python带cookie发包demo
以登录和发布新浪微博信息为例
1 def sendMsgToSina(username, password,msg):
2 loginUrl = "http://login.sina.com.cn/sso/login.php";
3 value = {"service" : "miniblog",
4 "encoding" : "utf-8",
5 "gateway" : "1",
6 "savestate" : "7",
7 "username" : username,
8 "password" : password};
9 cookie = cookielib.CookieJar();
10 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie));
11 urllib2.install_opener(opener);
12 data = urllib.urlencode(value);
13 #req = urllib2.Request(loginUrl, data);
14 #res = opener.open(req);
15 res = urllib2.urlopen(loginUrl, data);
16 #print res;
17
18 publishUrl = "http://t.sina.com.cn/mblog/publish.php";
19 #print msg;
20 param = "content=" + msg.encode("utf-8");
21 req = urllib2.Request(publishUrl, param);
22 req.add_header("Referer", "http://t.sina.com.cn/");
23 #opener.open(req);
24 res = urllib2.urlopen(req);
25 print res.read();
2 loginUrl = "http://login.sina.com.cn/sso/login.php";
3 value = {"service" : "miniblog",
4 "encoding" : "utf-8",
5 "gateway" : "1",
6 "savestate" : "7",
7 "username" : username,
8 "password" : password};
9 cookie = cookielib.CookieJar();
10 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie));
11 urllib2.install_opener(opener);
12 data = urllib.urlencode(value);
13 #req = urllib2.Request(loginUrl, data);
14 #res = opener.open(req);
15 res = urllib2.urlopen(loginUrl, data);
16 #print res;
17
18 publishUrl = "http://t.sina.com.cn/mblog/publish.php";
19 #print msg;
20 param = "content=" + msg.encode("utf-8");
21 req = urllib2.Request(publishUrl, param);
22 req.add_header("Referer", "http://t.sina.com.cn/");
23 #opener.open(req);
24 res = urllib2.urlopen(req);
25 print res.read();
方法大概是可以在一个opener里安装一个cookie,下次POST的时候就会自动带上这个cookie。