Python基础爬虫之百度翻译
代码
#coding utf-8
import requests
import json
class BaiduFanyi:
def __init__(self,trans_str):
self.trans_str = trans_str
self.lang_detect_url = "https://fanyi.baidu.com/langdetect"
self.trans_url ='https://fanyi.baidu.com/transapi'
self.headers ={"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}
def parse_url(self,url,data): #发送post请求,获取响应
response = requests.post(url,data=data,headers=self.headers)
ret= json.loads(response.content.decode())
return ret
def get_ret(self,dict_response):#提取翻译的结果
ret = dict_response["data"][0]["dst"]
print("result is :",ret)
def run(self):#实现主要逻辑
#1.获取语言