用Python实现一个程序,他能够获取所有我关注的人的最新的一条微博,并按照时间排序
时间: 2023-06-01 16:04:10 浏览: 71
由于需要获取微博数据,需要使用微博开放平台提供的API接口。以下是实现代码:
```python
import requests
import json
import datetime
# 替换成自己的APP_KEY和APP_SECRET
APP_KEY = 'your_app_key'
APP_SECRET = 'your_app_secret'
# 获取access_token
def get_access_token():
url = 'https://api.weibo.com/oauth2/access_token'
data = {
'grant_type': 'client_credentials',
'client_id': APP_KEY,
'client_secret': APP_SECRET
}
response = requests.post(url, data=data)
return json.loads(response.text)['access_token']
# 获取关注列表
def get_friends_list(access_token):
url = 'https://api.weibo.com/2/friendships/friends.json'
params = {
'access_token': access_token
}
response = requests.get(url, params=params)
return json.loads(response.text)['users']
# 获取最新微博
def get_latest_weibo(access_token, uid):
url = 'https://api.weibo.com/2/statuses/user_timeline.json'
params = {
'access_token': access_token,
'uid': uid,
'count': 1
}
response = requests.get(url, params=params)
return json.loads(response.text)['statuses'][0]
# 获取时间戳
def get_timestamp(time_str):
return datetime.datetime.strptime(time_str, '%a %b %d %H:%M:%S %z %Y').timestamp()
if __name__ == '__main__':
access_token = get_access_token()
friends_list = get_friends_list(access_token)
latest_weibos = []
for friend in friends_list:
latest_weibo = get_latest_weibo(access_token, friend['id'])
latest_weibos.append(latest_weibo)
latest_weibos.sort(key=lambda x: get_timestamp(x['created_at']), reverse=True)
for weibo in latest_weibos:
print(weibo['text'], weibo['created_at'])
```
程序的主要流程如下:
1. 获取access_token,用于后续API调用;
2. 获取关注列表;
3. 对于每个关注者,获取其最新的一条微博;
4. 将所有最新微博按照时间排序;
5. 输出所有最新微博的内容和时间。
需要注意的是,由于微博API返回的时间格式为字符串,需要转换成时间戳进行排序。同时,由于API调用需要网络连接,因此执行时间可能较长。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)