本文主要介绍关于python,前端,javascript的知识点,对【Python发送每日新闻】和【python+selenium】有兴趣的朋友可以看下由【A-L-Kun】投稿的技术文章,希望该技术
本文主要介绍关于python,前端,Javascript的知识点,对【Python 发送每日新闻】和【python+selenium】有兴趣的朋友可以看下由【A-L-Kun】投稿的技术文章,希望该技术和经验能帮到你解决你所遇的python,服务器,github相关技术问题。
python+selenium
文章目录 Python 发送每日新闻一、 简介1、 概述2、 环境配置3、 配置文件 二、 前端页面三、 获取数据1、 获取图片2、 获取新闻3、 制作数据 四、 发送邮件
Python 发送每日新闻 一、 简介 1、 概述
关注时事新闻,是新时代青年必须做的,那么,我们如何来快速获取新闻呢?
每天自动从网上找到新闻
自动整理新闻排版成一个html页面,发送到邮箱中
2、 环境配置
requests = "*"
fake-useragent = "*"
pyquery = "*"
3、 配置文件
{
"status": 200,
"data": [
{
"name": "A.L.Kun", "email": "3500515050@qq.com"}
],
"temp": [
]
}
data
里面存放我们需要发送的对象
status
:判断是否获取成功
二、 前端页面
我们使用前端知识,来设计页面,我的代码如下:
doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="token punctuation">"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>每日简报
title> <style> html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } * {
color: black; } input {
padding: 0; margin: 0; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block; } body {
line-height: 1; } ol, ul {
list-style: none; } blockquote, q {
quotes: none; } blockquote:before, blockquote:after, q:before, q:after {
content: ''; content: none; } table {
border-collapse: collapse; border-spacing: 0; } * {
text-decoration: none; margin: 0; }
style> <style> .main {
height: auto; width: 500px; margin: 100px auto; border: #a5a5a5 4px solid; border-radius: 10px; padding-bottom: 10px; } .main > h1 {
font: normal 500 33px "KaiTi_GB2312"; text-align: center; margin-bottom: 30px; margin-top: 10px; color: #436d7b; } .img_des {
font: normal 500 9px "Microsoft YaHei"; text-align: center; color: #b647a6; } img {
padding-left: 2px; border-radius: 10px; margin-bottom: 4px; } .big_line {
height: 5px; border-radius: 3px; width: 496px; background-color: #48745b; margin: 15px 0 5px 2px; } .small_line {
height: 3px; border-radius: 1px; width: 496px; background-color: #48745b; margin-left: 2px; } .body {
overflow: hidden; } .body .left {
float: left; background-color: #48745b; height: 100px; width: 300px; margin-left: 4px; } .body span {
margin-top: 10px; border-radius: 4px; } .body .right {
background-color: #48745b; height: 100px; width: 170px; float: right; margin-right: 4px; } .left h1 {
color: white; font: normal 500 33px "KaiTi_GB2312"; text-align: center; padding-top: 2px; } .left h2 {
color: white; font: normal 500 20px "KaiTi_GB2312"; text-align: center; border-top: white 2px solid; margin-top: 10px; padding-top: 6px; } .right h1{
text-align: center; border-top: #48745b 4px solid; border-left: #48745b 4px solid; border-right: #48745b 4px solid; border-radius: 4px; background-color: white; font: normal 600 18px "KaiTi_GB2312"; color: #48745b; margin-top: 11px; margin-bottom: 11px; } .right h3{
text-align: center; border: #48745b 4px solid; border-radius: 4px; background-color: white; font: normal 600 18px "KaiTi_GB2312"; color: #48745b; } .content div {
margin: 5px 2px 0 2px; padding: 10px 0 10px 10px; } .content p {
margin-top: 5px; font: normal 500 18px "KaiTi_GB2312"; }
style>
head> <body> <div class="main"> <h1>每日简报
h1> <a href="https://www.bing.com/search?q=%E6%82%89%E5%B0%BC%E5%A5%A5%E6%9E%97%E5%8C%B9%E5%85%8B%E5%85%AC%E5%9B%AD&form=hpcapt&mkt=zh-cn" target="_blank"> <img src="https://www.bing.com/th?id=OHR.BarcelonaPop_ZH-CN3687855585_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp" alt="Bing每日一图" width=496px>
a> <p class="img_des">悉尼奥林匹克公园里的湾标了望台,澳大利亚 (© ai_yoshi/Getty Images)
p> <div> <div class="header"> <div class="big_line">
div> <div class="small_line">
div>
div> <div class="body"> <span class="left"> <h1>每日早报
h1> <h2>NEWS TODAY
h2>
span> <span class="right"> <h1>2022年7月12日
h1> <h3>星期二
h3>
span>
div> <div class="content"> <div>
div>
div>
div>
div>
body>
html>
三、 获取数据 1、 获取图片
调用必应每日一图的接口,获取图片
# !/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "getImg.py"
__time__ = "2022/7/12 11:20"
"""获取到每日图片"""
from requests import get
from fake_useragent import UserAgent
def getResp():
url = "https://cn.bing.com/HPImageArchive.aspx" # 这里使用的是bing每日图片链接
resp = get(url, headers={ # 发送请求
"user-agent": UserAgent().random,
}, params={
"format": "js", # 返回JSON数据
"idx": 1, # 获取前一天的图片
"n": 1
})
# print(resp)
return resp.json()
def main1():
src = getResp()
url_img = "https://www.bing.com" + src["images"][0]["url"]
title = src["images"][0]["copyright"]
url_title = src["images"][0]["copyrightlink"]
return {
"url_img": url_img,
"title": title,
"url_title": url_title
} # 返回图片数据
if __name__ == '__main__':
print(main1())
2、 获取新闻
调用接口,获取每日新闻
__author__ = "A.L.Kun"
__file__ = "getInfo.py"
__time__ = "2022/7/12 10:08"
"""获取到每日新闻"""
from requests import get
from fake_useragent import UserAgent
def get_resp():
url = "https://news.topurl.cn/api"
resp = get(url, headers={
"user-agent": UserAgent().random
}, params={
"count": 20,
})
resp.encoding = resp.apparent_encoding
return resp.json()
def main2():
data_ = get_resp()
temp = []
for i in data_["data"]['newsList']:
temp.append({
"content": i["title"],
})
return temp
if __name__ == '__main__':
print(main2())
3、 制作数据
__author__ = "A.L.Kun"
__file__ = "GenHtml.py"
__time__ = "2022/7/12 14:21"
""" 生成HTML页面 """
from getImg import main1
from getInfo import main2
import datetime
from pyquery import PyQuery
def get_timer():
"""获取今天的时间"""
week = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
now = datetime.datetime.now()
time_ = now.strftime("%Y年%m月%d日")
week_ = week[int(now.strftime("%w"))]
return time_, week_
img = main1()
data = main2()
time_, week_ = get_timer()
def main3():
html = PyQuery(filename="./templates/index.html")
html(".right h1").text(time_)
html(".right h3").text(week_)
html(".img_des").text(img["title"])
html(".main a").attr("href", img["url_title"])
html(".main a img").attr("src", img["url_img"])
cont = html(".main .content div")
for index, item in enumerate(data):
str_ = f"{
index + 1}. {
item['content']}"
p = " %s
" % str_
cont.append(p)
return html.outer_html()
if __name__ == '__main__':
print(main3())
四、 发送邮件
__author__ = "A.L.Kun"
__file__ = "main.py"
__time__ = "2022/7/12 15:12"
import sys
from GenHtml import time_, week_, main3
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from functools import wraps
import json
f = open("settings.json", "r", encoding="utf-8")
info = json.load(f)
if info["status"] != 200:
print("JSON数据读取错误!")
sys.exit(1)
subject = f'{
time_}新闻(建议使用电脑查看)'
html = main3()
def decorate(fun_):
username = 'liu.zhong.kun@foxmail.com'
password_pass = 'sadfadsg'
smtp = SMTP('smtp.qq.com', 587)
smtp.starttls()
smtp.login(username, password_pass)
@wraps(fun_)
def func_mail(*args, **kwargs):
fun_(smtp, username, *args, **kwargs)
smtp.quit()
smtp.close()
return func_mail
@decorate
def mail(smtp, username):
for receiver_ in info["data"]:
msgRoot = MIMEText(html, "html", "utf-8")
msgRoot["Subject"] = Header(subject, "utf-8")
msgRoot['From'] = formataddr(("A.L.Kun", username))
msgRoot['To'] = formataddr((receiver_["name"], receiver_["email"]))
smtp.sendmail(username, receiver_["email"], msgRoot.as_string())
print(receiver_["email"], ':发送完成')
if __name__ == '__main__':
mail()
总代码:https://github.com/liuzhongkun1/spider_/tree/master/autosend
本文《Python 发送每日新闻》版权归A-L-Kun所有,引用Python 发送每日新闻需遵循CC 4.0 BY-SA版权协议。