有道爬虫翻译

import urllib.request
import urllib.parse
import json
import time
import random
import hashlib

url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

while True:
    
    content = input("Input Content:")

    head = {}
    head['Referer'] = 'http://fanyi.youdao.com'
    head['User - Agent'] = 'User-Agent:Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'

    #反爬虫破解 https://blog.csdn.net/nunchakushuang/article/details/75294947
    u = 'fanyideskweb'
    d = content
    f = str(int(time.time()*1000) + random.randint(1,10))
    c = 'rY0D^0\'nM0}g5Mm1z%1G4'
    sign = hashlib.md5((u + d + f + c).encode('utf - 8')).hexdigest()

    data = {}

    #构建data
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = f
    data['sign'] = sign
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyform'] = 'fanyi.web'
    data['action'] = 'FY_BY_CLICKBUTTION'
    data['typoResult'] = 'true'

    data = urllib.parse.urlencode(data).encode('utf - 8')

    req = urllib.request.Request(url, data, head)
    response = urllib.request.urlopen(req)
    html = response.read().decode('utf - 8')
    #print(html)

    #整理输出
    target = json.loads(html)
    #print(target)
    print("Result : %s" % (target['translateResult'][0][0]['tgt']))
    for i in target['smartResult']['entries']:
        if i != '':
            print("%s" %i, end = '')
    #time.sleep(5)

你可能感兴趣的:(python)