爬虫实现百度翻译

import requests
import json
import sys
query_string = sys.argv[1]
headers = {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"}
data = {
    "query": query_string,
    "from": "zh",
    "to": "en"
}
url = "https://fanyi.baidu.com/basetrans"
response = requests.post(url, headers=headers, data=data)
fanyi_dict = json.loads(response.content.decode())
print("result:", fanyi_dict["trans"][0]["dst"])



在命令行执行这个py文件 :~/cp/demo/pachong/day03$ python3 fanyi.py 录取
result: Admission

sys是关于命令行参数的包

 

import requests
import json
# import sys


class FanyiSpider:
    def __init__(self, query_string):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"}
        self.fan_url = "https://fanyi.baidu.com/basetrans"
        self.detect_url = "https://fanyi.baidu.com/langdetect"
        self.query_string = query_string

    def parse_url_dect(self):
        data = {"query": self.query_string}
        response = requests.post(self.detect_url, data=data, headers=self.headers)
        # print(response.content.decode())
        dict = json.loads(response.content.decode())["lan"]
        return dict

    def parse_url(self, dict):
        if dict == "en":
            data = {"query": self.query_string, "from": "en", "to": "zh"}
        else:
            data = {"query": self.query_string, "from": "zh", "to": "en"}
        response = requests.post(self.fan_url, data=data, headers=self.headers)
        trans_sen = json.loads(response.content.decode())["trans"][0]["dst"]
        return trans_sen

    def run(self):
        # 1.发送请求获取响应
        dict = self.parse_url_dect()
        # print(dict)
        res = self.parse_url(dict)
        print("res:", res)


if __name__ == "__main__":
    a = input("要翻译的句子:")
    fanyi = FanyiSpider(a)
    fanyi.run()



结果:
要翻译的句子:hello
res: 你好

 

你可能感兴趣的:(python)