跳转至

Python练习:requests和json

题目1

请大家使用 pip install requests 命令安装好 requests 库。

使用文档可以参考:http://cn.python-requests.org/zh_CN/latest/


github 提供了 REST API 接口,可以获取我们论坛上某个帖子里面所有跟帖的信息。

比如,我们要获取 论坛ID 为1 的帖子所有跟帖的信息,只需要访问

https://api.github.com/repos/baiyueheiyu/python3vip-forum/issues/1/comments

返回的响应消息体是json格式的字符串,如下所示

image

这是一个json数组, 其中每个元素对应一个跟帖的信息。 记录的信息包括了:谁发言的, 发言内容是什么等等。 如上图中红圈部分所示。

请求大家写一个程序, 把跟帖中所有 白月黑羽发言的信息 抓取出来 写到一个文件中。

最后调用notepad++ 打开该文件

您需要高效学习,找工作? 点击咨询 报名实战班

点击查看学员就业情况

题目1-答案

import requests
from pprint import pprint
from subprocess import Popen


res = requests.get('https://api.github.com/repos/baiyueheiyu/python3vip-forum/issues/1/comments')

# 将返回结果转为 python 中的list 对象
commentsList = res.json()

with open('d:/baiyue.txt','w',encoding='utf8') as f:
    for comment in commentsList:
        # 如果是baiyueheiyu的发言,写入文件
        if comment['user']['login'] == 'baiyueheiyu':
            f.write(comment['body'])
            f.write('\n---------------\n')

# notepad++程序路径, 由于路径中有空格
# 所以需要双引号括起来,这是Windows shell的语法
notepadexepath = r'"d:\Program Files (x86)\Notepad++\notepad++.exe"'

# 调用notepad++ 打开 
Popen(args=f'{notepadexepath} d:/baiyue.txt', shell=True)