Python3-网页爬取-post方式实现百度翻译

#请求方式 post
from urllib import request,parse
import json

def fanyi(content):


    data={
        'kw':content
    }
    data=parse.urlencode(data)
    # print(len(data))
    base_url = 'http://fanyi.baidu.com/sug'

    # Post
    headers = {
        "Content-Length": len(data),  # 动态计算data长度
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
    }
    #字符串转bytes
    req=request.Request(url=base_url,data=bytes(data,encoding='utf-8'),headers=headers)
    response=request.urlopen(req)
    html=response.read()
    html=html.decode('utf-8')

    json_data=json.loads(html)#梳理成json格式
    print(json_data)

    #整理数据
    for item in json_data['data']:
        print(item['k'],item['v'])

if __name__=='__main__':

    content = input('请输入您要翻译的内容:')
    fanyi(content)
 
 

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/apple/PycharmProjects/stage4/spider/20180305/05post.py
请输入您要翻译的内容:just
{'errno': 0, 'data': [{'k': 'just', 'v': 'adv. 正好; 刚才; 仅仅,只是; 刚要; adj. 公正的,合理的; 恰当的; 合法的; 正确'}, {'k': 'justice', 'v': 'n. 正义; 公正; 法律制裁; 审判员,法官;'}, {'k': 'justify', 'v': 'vt. 证明…有理; 为…辩护; 对…作出解释; vi. 整理版面; 证明合法;'}, {'k': 'just do it', 'v': ' 就这么干吧;'}, {'k': 'just now', 'v': ' 刚才;  刚刚; 现在; 立刻;'}]}
just adv. 正好; 刚才; 仅仅,只是; 刚要; adj. 公正的,合理的; 恰当的; 合法的; 正确
justice n. 正义; 公正; 法律制裁; 审判员,法官;
justify vt. 证明…有理; 为…辩护; 对…作出解释; vi. 整理版面; 证明合法;
just do it  就这么干吧;
just now  刚才;  刚刚; 现在; 立刻;


Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/zbrj12345/article/details/79916600
今日推荐