让我们一起爬 “百度翻译”

import requests
import json

inputStr = input("请输入要翻译的内容:")
fanyi_url = "https://fanyi.baidu.com/basetrans"
fanyi_headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36"}
fanyi_data = {
    "from": "zh",
    "to": "en",
    "query": inputStr
}

def getHtml(url):
    response = requests.post(url,data=fanyi_data,headers=fanyi_headers)
    return response.content.decode()
def getContent(response):
    content = json.loads(response)
    return content["trans"][0]["dst"]
def saveContent(content):
    file = "E:/fanyi/fanyi.txt"
    f = open(file, "a", encoding="utf-8")
    f.write(inputStr+" ---->> "+content+"\n")
    f.close()

if __name__ == '__main__':
    r = getHtml(fanyi_url)
    contentP = getContent(r)
    saveContent(contentP)
    print(inputStr+" ---->> "+contentP)
    print("存档成功")

 

你可能感兴趣的:(爬虫,python,爬取百度翻译,翻译)