本文主要是介绍[Python] 央视新闻联播推送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先要感谢大佬@Hangjau的基础代码
地址:https://www.52pojie.cn/forum.php … 2%CE%C5%C1%AA%B2%A5
楼上大佬的代码及云函数的部署都很详细,如若不会部署云函数以及安装依赖库的童鞋可以看看上面帖子中的教程
依赖库:
1、requests —— 网络请求
2、re —— 正则库
3、lxml —— 网页解析
4、time —— 时间库
5、yagmail —— 邮件发送
其中:3和5 在部署云函数时需要安装
修改说明:
楼上@Hangjau大佬的操作已十分完美,但是使用的网站更新很慢,有时候第二天、第三天都不更新,会出现推送不及时,对于我这样喜欢学习的人来说,有点心急(其实我是个新闻从业者,哈哈),主要修改了下面几个地方,让推送及时完备。
1、将原来获取数据的网站更改为CCTV新闻联播的官网数据,官方网站最迟在晚上9点半就会更新当天新闻联播的文字以及视频,保证了数据来源的及时准确。
2、在推送内容中将之前的纯文字完善为文字+视频
import re
import requests
from lxml import etree
import time
import yagmail# 设置请求头
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4651.0 Safari/537.36',
}
# 获取日期
timeStruct = time.localtime()
strTime = time.strftime("%Y%m%d", timeStruct)
str_time = int(strTime)-1 # 如果是上午8点以后推送的,括号外的“-1”要删除# 获取新闻
def hq_news():news = []url = f'https://tv.cctv.com/lm/xwlb/day/{str_time}.shtml'response = requests.get(url, headers=headers)response.encoding = 'RGB'resp = response.textetr = etree.HTML(resp)titles = etr.xpath("//div[@class='title']/text()")hrefs = etr.xpath("//li/a/@href")for title, href in zip(titles, hrefs):news_response = requests.get(href, headers=headers)news_response.encoding = 'RGB'news_resp = news_response.textnews_gz = '.*(<div class="cnt_bd"><!--repaste.body.begin-->.*?</div>).*'news_zw = re.findall(news_gz, news_resp)news_th = news_zw[0]news.append(f"<font color='#000079'><b>{title}</b></font>\n{news_th}视频地址:{href}\n\n\n")return news# 邮箱推送
def main(event, context):username = 'xxxxxxxx@163.com'password = 'xxxxxxxx'yag = yagmail.SMTP(user=username, password=password, host='smtp.163.com', port=465)content = hq_news()yag.send(to=['xxxxxxxx@qq.com'], subject=f'{str_time}新闻联播推送', contents=content)return '邮件发送成功'
提示:请将代码中第41、42、43行修改为你的发送邮件的邮箱账号和密码以及SMTP服务器地址;第45行修改为接收推送的邮箱地址。
本人测试了微信推送(使用pushplus),结果显示效果不好,而且视频链接不能打开,后期有时间再改一下了。
这篇关于[Python] 央视新闻联播推送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!