Python腾讯微博上传图片

0

好吧下午弄完腾讯微博登录模拟,发送文章信息,我实在是等不及实现发送图片了,于是我挤了点时间,动画片都没看来把下面的写完。

首先我们看一下图片上传时的信息:

腾讯微博浏览器上传信息

OK,我们假设已经处于登录状态了,发送图片微博和文字微博差不多,只不过上传图片和添加一下图片信息就可以了。
在文字微博的参数加入图片信息如下:

formdata = {
	"content" : msg,
	"pic" : "", # 上传图片获得的链接
	"countType" : "",
	"pgv_ref" : "web.base.master.talkBox.btnApolloMyHome",
	"apiType" : "14",
};

好了,最重要的就是上次图片操作,代码如下:

def getPicUrl(imgmsg): # 读取图片连接
    if imgmsg == None:
        return None;
    return imgmsg.split(",")[1].split("{")[1].split("\"")[3].replace("\/", "/");
def send_post(cookie, msg, path = None, name = None): # 参数依次是:cookie,文字信息,图片地址,图片名字
    picurl = None;
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie));
    opener.addheaders = [("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36")];
    urllib2.install_opener(opener);
     
    if (path != None and name != None):
        BOUNDARY = "----------" + str(time.time() * 100); # 定义数据分割线
 
        uploadmsg = """--%s
Content-Disposition: form-data; name="Filename"
 
%s
--%s
Content-Disposition: form-data; name="filename"; filename="%s"
Content-Type: application/octet-stream
 
%s
--%s
Content-Disposition: form-data; name="Upload"
 
Submit Query
--%s--
""" % (BOUNDARY, name, BOUNDARY, name, open(path, "rb").read(), BOUNDARY, BOUNDARY);
        upload = urllib2.Request("图片上传地址");
        upload.add_data(uploadmsg);
        upload.add_header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        upload.add_header("Referer", "http://api.t.qq.com/proxy.html");
        uploadConn = urllib2.urlopen(upload);
          
        picurl = getPicUrl(uploadConn.read());

把连接放到微博信息里面就一样的了。

DEMO下载,请先配置cnf.ini。