【Python】使用POST方式抓取有道翻譯結果


1.安裝requests庫

 

 

 

 

2.打開有道翻譯,按下F12,進入開發者模式,輸入我愛青青,點擊Network,再點擊XHR

 

 

3、撰寫爬蟲

import requests
import json

# 使用有道翻譯
def get_translate_date(word=None):
# 錯誤 url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
url = 'http://fanyi.youdao.com/translate'
Form_data={
'i': word,
'from':'AUTO',
'to':'AUTO',
'smartresult':'dict',
'client':'fanyideskweb',
'salt':'15477850915136',
'sign': 'cdedfb035de1ac1cf55109a1afb7a2c1',
'ts':'1547785091513',
'bv':'777cf4e24b15a2b93e1c9237866d73ad',
'doctype':'json',
'version':'2.1',
'keyfrom':'fanyi.web',
'action':'FY_BY_REALTIME',
'typoResult':'false',
}
# 請求表單數據
response = requests.post(url, data=Form_data)
# 將JSON格式字符串轉字典
content = json.loads(response.text)
# 打印翻譯后的數據
print(content['translateResult'][0][0]['tgt'])

if __name__ == '__main__':
get_translate_date('我愛青青')
4.翻譯結果

 

5.錯誤處理(KeyError: 'translateResult')

Python的字典一般都直接查找key ,如果在查找的key不存在的時候就會報:KeyError:

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

改為:url = 'http://fanyi.youdao.com/translate'
---------------------
作者:俊俊~
來源:CSDN
原文:https://blog.csdn.net/qq_40602000/article/details/86540928
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM