利用Python爬取翻译网站的翻译功能

要爬取的网站:http://fy.iciba.com/
https://blog.csdn.net/weixin_43808690/article/details/87886075 原文链接
代码:

from urllib import request,parse
import json
class fanyi():
    def translate(word):
        #确定URL
        base_url="http://fy.iciba.com/ajax.php?a=fy"
        data={
            "f":"auto",
            "t":"auto",
            "w":word
        }
        data_str=parse.urlencode(data)
        # url=base_url+data_str

        #伪装
        header={"User-Agent":" Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"}

        #封装
        response=request.Request(url=base_url,headers=header,data=bytes(data_str,encoding="utf-8"))
        req=request.urlopen(response).read().decode("utf-8")
        obj=json.loads(req)
        return obj

    if __name__ == ‘__main__‘:
        word = input("请输入需要翻译的词句:")
        trans_word = translate(word)
        print(trans_word)
        current_state=trans_word["status"]
        #在这里判断中译英
        if current_state==1:
            current_content=trans_word["content"]
            print(current_content["out"])
        #否则则汉译英
        else:
            current_content0=trans_word["content"]
            print(current_content0["word_mean"])

fanyi()

相关推荐