python3爬虫使用post请求实现百度翻译

使用post请求实现百度翻译
#!/usr/bin/python
# -*- coding: utf-8 -*-

# 0. 分析百度翻译
# http://fanyi.baidu.com/basetrans

import requests
import json

# 1. 定义构建请求参数
url = "http://fanyi.baidu.com/basetrans"

#定义请求头
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",
    "X-Requested-With": "XMLHttpRequest"
}

# 定义参数
query = input("请输入翻译内容:")
params = {
    "query": query,
    "from": "zh",
    "to": "en"
}

# 2. 发送请求获取响应数据
response = requests.post(url,params,headers = headers)

# 3. 处理数据
resp_string = response.text
# 将字符串转换成python数据格式
data = json.loads(resp_string)
print("翻译结果:{}".format(data['dict']['word_means'][0]))

你可能感兴趣的:(爬虫)