python3获取每日新闻
之前给大家分享的pyhon3抓取每日心语新闻,最近公众号好像不更新了,故给大家换了个新的.
软件环境: python3.x
cat /root/soft_shell/send_new.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @IDE :PyCharm @Author :rocdk890 @Date :2024/5/31 16:19 ''' import base64 import json import datetime import hashlib import hmac import time import urllib.parse import requests import random import re def fetch_news(token): url = "https://v2.alapi.cn/api/zaobao" payload = f"token={token}&format=json" headers = {'Content-Type': "application/x-www-form-urlencoded"} response = requests.request("POST", url, data=payload, headers=headers) newdata = json.loads(response.text) date = newdata['data']['date'] news = newdata['data']['news'] return date, news def send_to_dingding(message, access_token): timestamp = str(round(time.time() * 1000)) # dingding 加签密钥 secret = 'SECxxxxxxxxxxxxxxxxxxxxx' secret_enc = secret.encode('utf-8') string_to_sign = '{}\n{}'.format(timestamp, secret) string_to_sign_enc = string_to_sign.encode('utf-8') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = urllib.parse.quote(base64.b64encode(hmac_code)) headers = { "Content-Type": "application/json", "Charset": "UTF-8" } data = { "msgtype": "text", "text": { "content": message } } url = 'https://oapi.dingtalk.com/robot/send?access_token=' + access_token + "×tamp=" + timestamp + "&sign=" + sign response = requests.post(url, json=data, headers=headers) if response.status_code != 200: raise Exception("Failed to send dingding message") def main(): token = "xxxxxxxxxxxxxxxx" access_token = "bxxxxxxxxxxxxxxxxxxxxxxxxxxxx" date, news = fetch_news(token) message = f"时间: {date}\n新闻内容:\n" + "\n\n".join(news) send_to_dingding(message, access_token) if __name__ == "__main__": main()
评论: