Python爬取百度翻译
程序员文章站
2022-05-04 12:04:18
...
import requests
import json
class BaiDu(object):
#数据初始化
def __init__(self,word):
self.url = 'https://fanyi.baidu.com/sug'
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'
}
self.data = {
# 'query':word,
'kw': word
}
#post得response的json格式
def get_data(self):
response = requests.post(self.url,headers=self.headers,timeout=3,data=self.data)
return response.content
def analyse_data(self,data):
dict_data = json.loads(data)
# try:
print(dict_data["data"][0]["v"])
# except:
# print(dict_data["data"][0]["dist"])
def run(self):
# url
# headers
# post发送请求得到响应
response = self.get_data()
# 将response的json转成转成字典
self.analyse_data(response)
# 解析响应
if __name__ == '__main__':
while(1):
try:
word = input("请输入需要翻译的词/句子:")
translate = BaiDu(word)
translate.run()
except:
print("找不到,请重新输入")