举例json和POST爬取百度翻译

from urllib import request,parse
import json

def fanyi(content):
base_url = 'http://fanyi.baidu.com/sug'
data = {
'kw': content
}
data = parse.urlencode(data)
headers = {
'Content-Length': len(data),
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
   #创建请求对象,因为post请求,所有要加入headers头和data数据
res = request.Request(base_url,data=bytes(data,encoding="utf-8"),headers=headers)
response = request.urlopen(res)
html = response.read()
   #json.loads将json格式转化成字符串类型
result = json.loads(html)
for item in result['data']:
print(item['k'],item['v'])

if __name__ == "__main__":
while True:
content = input("请输入所需要翻译的内容:")
if content == 'q':
print("已关闭翻译界面!!!")
break
fanyi(content)

posted on 2018-03-26 22:14  健步如飞的老大爷  阅读(229)  评论(0编辑  收藏  举报

导航