from urllib import request,parse
import json
# 翻譯函數
def fanyi(msg):
#參數封裝
data = {
"kw": content
}
#參數拼接以及轉碼
data = parse.urlencode(data)
#請求地址
base_url = "http://fanyi.baidu.com/sug"
# Post
headers = {
"Content-Length": len(data), #動態計算d··ata長度
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
}
#封裝一個request對象(地址,數據,headers)
req = request.Request(url=base_url, data=bytes(data, encoding="utf-8"), headers=headers)
#發起請求,並得到響應
response = request.urlopen(req)
#讀取內容
html = response.read()
html = html.decode("utf-8") #轉碼
json_data = json.loads(html)#使用json格式化
#print(json_data)
# 整理數據
for item in json_data["data"]:
print(item["k"], item["v"])
if __name__ == "__main__":
#輸入數據
content = input("請輸入您要翻譯的內容:")
#翻譯
fanyi(content)
# https://tbmsg.baidu.com/gmessage/get?mtype=1&_=1521032999727
# https://tieba.baidu.com/f?kw=qq%E7%82%AB%E8%88%9E%E6%89%8B%E6%B8%B8&ie=utf-8&pn=50