python3获取每日新闻

post by rocdk890 / 2024-5-31 17:20 Friday linux技术
之前给大家分享的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 + "&timestamp=" + 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()
夜空- 本站版权
1、本站所有主题由该文章作者发表,该文章作者与夜空享有文章相关版权
2、其他单位或个人使用、转载或引用本文时必须同时征得该文章作者和夜空的同意
3、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责
4、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
5、原文链接:blog.slogra.com/post-811.html

标签: api python3 爬虫 新闻 每日

评论: