1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import requests import random import hashlib import time
class TranslationSpider: def __init__(self, word): self.base_url = 'http://fanyi.youdao.com/?keyfrom=fanyi-new.logo' self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule' self.session = requests.session() self.headers = { 'Referer': 'http://fanyi.youdao.com/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66 ' } self.word = word self.data = {}
def generator_data(self): ts = str(int(time.time() * 1000)) salt = ts + str(random.randint(0, 10)) sign = "fanyideskweb" + self.word + salt + "Tbh5E8=q6U3EXe+&L[4c@" md5 = hashlib.md5() md5.update(sign.encode()) sign = md5.hexdigest() self.data = { "i": self.word, "from": "AUTO", "to": "AUTO", "smartresult": "dict", "client": "fanyideskweb", "salt": salt, "sign": sign, "lts": ts, "bv": "b286f0a34340b928819a6f64492585e8", "doctype": "json", "version": "2.1", "keyfrom": "fanyi.web", "action": "FY_BY_REALTlME" }
def get_request(self): self.session.get(url=self.base_url, headers=self.headers) response = self.session.post(url=self.url, data=self.data, headers=self.headers).json() return response
def parse_json(self, json): tgt = json['translateResult'][0][0]['tgt'] entries = json['smartResult']['entries'] print('英文{}翻译结果为:{}'.format(self.word, tgt)) print(''.join(entries))
def run(self): self.generator_data() self.parse_json(self.get_request())
if __name__ == '__main__': while True: w = input('输入需要翻译的英文:') if w == 'exit0': print('退出成功!') break spider = TranslationSpider(w) spider.run()
|