Python 小冰颜值测试

据上次的PHP版小冰颜值测试,这次学习了Python,所以写了一个Python版本的

程序清单

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017-05-31 18:19:42
# @Author  : sungod (xtype@qq.com)
# @Link    : http://xtype.cn/

import urllib2
import urllib
import base64
import json
import sys
import os
import time
import re
import cookielib


class Ice(object):
    """docstring for Ice"""
    ice_page = 'https://kan.msxiaobing.com/ImageGame/Portal?task=yanzhi'
    ice_api = 'https://kan.msxiaobing.com/Api/ImageAnalyze/Process?{}'
    upload_file_api = 'http://kan.msxiaobing.com/Api/Image/UploadBase64'

    def __init__(self, img_data):
        self.img_data = img_data

    def upLoadFile(self):
        imgdataBase64 = base64.b64encode(self.img_data)
        req = urllib2.Request(self.upload_file_api, imgdataBase64)

        try:
            response = urllib2.urlopen(req)
        except Exception:
            print ('Server Error.')
            exit()
        else:
            return response.read()

    def test(self):
        ret = json.loads(self.upLoadFile())
        data = {
            'MsgId': '%d063' % int(time.time()),
            'CreateTime': int(time.time()),
            'Content[imageUrl]': '%s%s' % (ret['Host'], ret['Url']),
        }

        param = {
            'service': 'yanzhi',
        }

        api = self.ice_api.format(urllib.urlencode(param))

        cookie = cookielib.CookieJar()
        handler = urllib2.HTTPCookieProcessor(cookie)
        opener = urllib2.build_opener(handler)

        opener.open(self.ice_page)

        req = urllib2.Request(
            api,
            urllib.urlencode(data),
            headers={'Referer': self.ice_page},
        )

        response = opener.open(req)
        if response.code == 200:
            ret = json.loads(response.read())
            if ret is None:
                print 'Server Error.'
                exit()
            if 'content' in ret:
                print str(ret['content']['text'].encode('utf-8'))
                print ret['content']['imageUrl']
                exit()
        print 'Server Error.'


if __name__ == '__main__':
    if len(sys.argv) == 1:
        print 'Error: iceface.py [localfile|http].'
        exit()

    # is localfile?
    if not os.path.isfile(sys.argv[-1]):
        rec = re.match(r'^[a-zA-z]+://[^\s]*$', sys.argv[-1])
        if rec is None:
            print 'Param error.'
            exit()
        try:
            print 'Download File...'
            req = urllib2.urlopen(sys.argv[-1])
        except Exception:
            print 'Download File error.'
            exit()
        else:
            imgdata = req.read()
    else:
        with open(sys.argv[-1], 'rb') as f:
            imgdata = f.read()
    o = Ice(imgdata)
    o.test()

效果图

效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,856评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,797评论 19 139
  • 最近剽猂一只猫实在太火了,而且各个领域的大牛给他背书 事件一:李笑来老师不但在公号、还在得到订阅专栏发出...
    Ameizeng阅读 2,885评论 0 0
  • 文/李智彬秋风卷起清波乱,雾绕轻尘满。山峦若隐水连绵,柳岸蝉鸣水映荷花颜。闲谈且饮清香茗,遥望山成岭。落花流水相婵...
    李智彬阅读 2,844评论 1 1