Python爬虫教程-06-爬虫实现百度翻译(requests)

python爬虫

上一篇介绍了怎么使用浏览器的【开发者工具】获取请求的【地址、状态、参数】以及使用python爬虫实现百度翻译功能【urllib】版

上一篇链接:NicePython:Python爬虫教程-05-python爬虫实现百度翻译

本篇介绍使用python爬虫实现百度翻译功能【requests】版

原文:

https://blog.csdn.net/qq_40147863/article/details/81591145blog.csdn.net

使用requests,必须先添加requests包

安装requests

如果使用Anaconda环境,使用下面命令:

conda install requests

如果不是,就自己手动在【PyCharm】>【file】>【settings】>【Project Interpreter】>【+】>【requests】>【install】

具体操作截图:

《Python爬虫教程-06-爬虫实现百度翻译(requests)》
《Python爬虫教程-06-爬虫实现百度翻译(requests)》

直接献上代码

# 百度翻译
# 添加包的方法在上面
import requests
import json

def fanyi(keyword):
    url = 'http://fanyi.baidu.com/sug'

    # 定义请求参数
    data = {
        'kw': keyword
    }

    # 发送请求,抓取信息
    res = requests.post(url,data=data)

    # 解析结果并输出
    str_json = res.text

    myjson = json.loads(str_json)
    info = myjson['data'][0]['v']
    print(info)

if __name__=='__main__':
    while True:
        keyword = input('请输入翻译的单词:')
        if keyword == 'q':
            break
        fanyi(keyword)

代码运行

《Python爬虫教程-06-爬虫实现百度翻译(requests)》
《Python爬虫教程-06-爬虫实现百度翻译(requests)》

没错,requests版就是这么简洁,只不过需要加载requests包
使用python爬虫实现百度翻译功能(requests)版就介绍到这里了

    原文作者:NicePython
    原文地址: https://zhuanlan.zhihu.com/p/62247454
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞