要使用Python自动发微博,你可以按照以下步骤进行操作:
创建应用
在新浪微博开放平台创建一个应用,以获取`APP_KEY`和`APP_SECRET`。
获取`ACCESS_TOKEN`
通过调用`https://api.weibo.com/oauth2/authorize`接口,使用`APP_KEY`和`APP_SECRET`获取`CODE`。
然后使用`CODE`调用`https://api.weibo.com/oauth2/access_token`接口获取`ACCESS_TOKEN`。
发布微博
使用获取到的`ACCESS_TOKEN`,调用`https://api.weibo.com/2/statuses/update.json`接口发布微博。
import requests
import json
配置参数
APP_KEY = '你的APP_KEY'
APP_SECRET = '你的APP_SECRET'
REDIRECT_URI = '你的回调地址'
获取ACCESS_TOKEN
def get_access_token(code):
url = f'https://api.weibo.com/oauth2/access_token?client_id={APP_KEY}&client_secret={APP_SECRET}&grant_type=authorization_code&code={code}&redirect_uri={REDIRECT_URI}'
response = requests.get(url)
if response.status_code == 200:
return response.json().get('access_token')
else:
return None
发布微博
def post_status(access_token, status):
url = 'https://api.weibo.com/2/statuses/update.json'
payload = {
'access_token': access_token,
'status': status
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
if response.status_code == 200:
return response.json()
else:
return None
主程序
if __name__ == '__main__':
假设这里获取到了CODE
code = '你的CODE'
access_token = get_access_token(code)
if access_token:
发布微博
status = '这是自动发布的微博内容'
result = post_status(access_token, status)
if result and result.get('error_code') == 0:
print('微博发布成功!')
else:
print('微博发布失败,请检查内容或网络连接')
else:
print('获取ACCESS_TOKEN失败,请检查参数或网络连接')
请注意,微博的API可能会更新,所以具体的参数和接口地址可能会有所变化。确保在编写代码前查看最新的开发文档,并根据实际情况调整代码。
另外,如果你需要定时任务来自动发微博,可以使用Python的`schedule`库或其他定时任务库来实现。