千钻公会让前端飞工具癖

用Python3薅"百度翻译"的羊毛

2018-11-28  本文已影响112人  zhaoolee

薅"百度翻译"羊毛的起因 :

最近博主在https://unsplash.com搜索免费可商用图片的时候, 发现...

如果我们能用Python3把"苹果"翻译成"apple", 然后用Python3爬虫批量获取图片就完美了

爬虫获取图片链接并不难, Unsplash本身提供了开源的接口(以apple为例): https://unsplash.com/napi/search/photos?query=apple

如何用Python3把"苹果"翻译成"Apple"?

怎么用?


吐槽一下, 在python2即将被废弃的今天, 百度提供的示例Demo居然只有python2版本


import http.client
import hashlib
import urllib.parse
import random
import json


def baiduTranslate(q="苹果", fromLang="zh", toLang="en"):
    appid = '' #你的appid(这里是必填的, 从百度 开发者信息一览获取)
    secretKey = '' #你的密钥(这里是必填的, 从百度 开发者信息一览获取)

    httpClient = None
    myurl = '/api/trans/vip/translate'
    salt = random.randint(32768, 65536)
    sign = appid+q+str(salt)+secretKey
    m1 = hashlib.md5()
    m1.update(sign.encode())
    sign = m1.hexdigest()
    myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    result = ""
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
        #response是HTTPResponse对象
        response = httpClient.getresponse()
        result = response.read()
    except Exception as e:
        print (e)
    finally:
        if httpClient:
            httpClient.close()

    return result


def main():
    print(json.loads(baiduTranslate(q="苹果")))

if __name__ == '__main__':
    main()

运行效果

  • 黄河之水天上来, 奔流到海不复回
    The water of the Yellow River rises in the sky and runs to the sea and never returns.
  • 天若有情天亦老, 人间正道是沧桑
    If heaven is sentimental and heaven is old, the right way on earth is vicissitudes of life.

小结:

上一篇下一篇

猜你喜欢

热点阅读