代码拉取完成,页面将自动刷新
import requests
import json
class BaiduTranslator:
def __init__(self):
self.headers = {"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}
def langdetect(self, words):
url = 'http://fanyi.baidu.com/langdetect'
data = {
'query': words
}
response = requests.post(url, data=data)
lang_info = json.loads(response.content.decode())
return lang_info['lan']
def translator(self, words):
url = 'http://fanyi.baidu.com/basetrans'
data = {
'query': words,
'from': self.langdetect(words)
}
data['to'] = 'zh' if data['from'] == 'en' else 'en'
response = requests.post(url, data=data, headers=self.headers)
lang_info = response.json()
return lang_info['trans'][0]['dst']
class YoudaoTranslator:
def __init__(self):
self.headers = {"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}
def translator(self, words):
url = 'http://m.youdao.com/translate'
data = {
'inputtext': words,
'type': 'AUTO'
}
response = requests.post(url, data=data, headers=self.headers)
html_str = response.content.decode()
ul_start = '<ul id="translateResult">'
li_start = '<li>'
li_end = '</li>'
ul_start_pos = html_str.find(ul_start) + len(ul_start)
li_start_pos = html_str.find(li_start, ul_start_pos) + len(li_start)
li_end_pos = html_str.find(li_end, ul_start_pos)
print(html_str[li_start_pos:li_end_pos])
class CibaTranslator:
def __init__(self):
self.headers = {"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}
def translator(self, words):
url = 'http://fy.iciba.com/ajax.php?a=fy'
data = {
'f': 'auto',
't': 'auto',
'w': words
}
response = requests.post(url, data=data, headers=self.headers)
info = response.json()
print(info['content']['out'])
if __name__ == '__main__':
youdao = YoudaoTranslator()
youdao.translator('测试')
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。