spider_使用urllib库 提交post请求,有道翻译案例

"""
使用urllib库 提交post请求, 有道翻译
"""

from urllib import request
from urllib import parse
import json
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0"}

# 构建参数字典
parame ={
#需翻译内容
"i":"你好",
"from":"AUTO",
"to":"AUTO",
"smartresult":"dict",
"client":"fanyideskweb",
"salt":"15596318223592",
"sign":"6095c71447feda2d528eb238e957c476",
"ts":"1559631822359",
"bv":"e2a78ed30c66e16a857c5b6486a1d326",
"doctype":"json",
"version":"2.1",
"keyfrom":"fanyi.web",
"action":"FY_BY_REALTlME"
}

# 将参数字典转成字符串
data = parse.urlencode(parame).encode()
# 将参数字典夹带到含有http请求(post)的字符串中,返回字符串
html=request.urlopen(url,data=data).read().decode()
# print(html)
# print(type(html))

#将字符串转换成json格式文件,把字符串转化为python对象 dict,list
pythonObj=json.loads(html)
# print(pythonObj)
# print(type(pythonObj))

# 提取信息
result=pythonObj["translateResult"][0][0]['tgt']
print(result)
posted @ 2019-06-05 10:32  猫有九命  阅读(190)  评论(0编辑  收藏  举报