【代码】利用Python每天自动发新闻到邮箱

简介: 【代码】利用Python每天自动发新闻到邮箱

前言

偶然间想到每天推送新闻给自己,在网上搜了下果然有轮子,不过代码跑不起来,于是自己改了下

https://blog.csdn.net/qq_42374697/article/details/122144486

# -*- coding: utf-8 -*-
"""
Created on Fri Dec 24 15:21:51 2021
@author: ABC
"""
# smtplib 用于邮件的发信动作
import smtplib
from email.mime.text import MIMEText
# email 用于构建邮件内容
from email.header import Header
# 用于构建邮件头
import json
import hashlib
import base64
import hmac
import os
import time
import requests
from urllib.parse import quote_plus
from lxml import etree
import urllib.request  # 提取网址数据
import gzip
def get_weather_data():
    city_name = '重庆'
    url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name)
    weather_data = urllib.request.urlopen(url1)
    weather_data = weather_data.read()
    weather_data = gzip.decompress(weather_data).decode('utf-8')
    weather_dict = json.loads(weather_data)
    return weather_dict
def show_weather(weather_data):
    # 将形参数据值即(return weather_dict)赋值给这里的weather_dict变量
    import requests
    from lxml import etree
    base_url = 'https://www.tianqi.com/chongqing/'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                             + 'Chrome/62.0.3202.94 Safari/537.36'}
    res = requests.get(base_url, headers=headers)
    html = res.text
    html = etree.HTML(html)
    riqi = html.xpath('//dl[@class="weather_info"]/dd[@class="week"]/text()')[0].replace(' ', ' ')
    tianqi = html.xpath('//dl[@class="weather_info"]/dd[@class="weather"]/span/b/text()')[0]
    now = ''.join(html.xpath('//dl[@class="weather_info"]/dd[@class="weather"]/p[@class="now"]//text()'))
    wendu = html.xpath('//dl[@class="weather_info"]/dd[@class="weather"]/span/text()')[0]
    shidu = html.xpath('//dl[@class="weather_info"]/dd[@class="shidu"]/b[1]/text()')[0]
    shidu1 = html.xpath('//dl[@class="weather_info"]/dd[@class="shidu"]/b[2]/text()')[0]
    shidu2 = html.xpath('//dl[@class="weather_info"]/dd[@class="shidu"]/b[3]/text()')[0]
    kongqi = html.xpath('//dl[@class="weather_info"]/dd[@class="kongqi"]/h5/text()')[0]
    pM = html.xpath('//dl[@class="weather_info"]/dd[@class="kongqi"]/h6/text()')[0]
    richu = html.xpath('//dl[@class="weather_info"]/dd[@class="kongqi"]/span/text()')[0]
    richu2 = html.xpath('//dl[@class="weather_info"]/dd[@class="kongqi"]/span/text()')[1]
    yu = html.xpath('//div[@class="weather_life300"]/ul/li[1]/a/p/text()')[0]
    weather_dict = weather_data
    if weather_dict.get('desc') == 'invilad-citykey':
        print('你输入的城市名有误,或者天气中心未收录你所在城市')
    elif weather_dict.get('desc') == 'OK':
        forecast = weather_dict.get('data').get('forecast')
        if '雨' in yu:
            tishi = '今日可能下雨,记得带伞哦!' + weather_dict.get('data').get('ganmao')
        else:
            tishi = +weather_dict.get('data').get('ganmao')
        b = '------重庆天气查询------\n' + \
            riqi + '\n' + '天气:' + tianqi + '\n' + '当前气温:' + now + '\n' + '温度:' + wendu + '\n' + shidu + '\n' + shidu1 + '\n' + shidu2 + '\n' + kongqi + '\n' + \
            pM + '\n' + richu + '\n' + richu2 + '\n' \
                                                '-----------------------' + '\n' \
                                                                            '明日天气:', forecast[1].get('type') + '\n' \
                                                                                                               '最高气温:', \
            forecast[1].get('high').replace('高温 ', '') + '\n' \
                                                         '最低气温:', forecast[1].get('low').replace('低温 ', '') + '\n' \
                                                                                                              '温馨提示:', tishi
        return b
def main_handler(arg1,agr2):
    pass
def jianbao():
    base_url = 'https://www.163.com/dy/media/T1603594732083.html'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                             + 'Chrome/62.0.3202.94 Safari/537.36'}
    # 获取新闻列表页
    res = requests.get(base_url, headers=headers)
    html = res.text
    html = etree.HTML(html)
    # 获取第一条新闻
    today_url = html.xpath("//ul[@class='list_box cur']/li/a/@href")[0]
    # 获取详情页数据
    resp_1 = requests.get(today_url, headers=headers).text
    html_1 = etree.HTML(resp_1)
    # 获取新闻详情
    news_list = html_1.xpath('//div[@class="post_body"]/p[2]//text()')[1:]
    a = '\n'.join(news_list)
    a = a.replace('365资讯简报,每天精选15条热点新闻简报1条微语,', '')
    return a
if __name__ == "__main__":
    # 发信方的信息:发信邮箱,QQ 邮箱授权码
    from_addr = 'xx@qq.com'
    password = 'xx'
    # 收信方邮箱
    to_addr = 'xx@qq.com'
    # 发信服务器
    smtp_server = 'smtp.qq.com'
    # 邮箱正文内容,第一个参数为内容,第二个参数为格式(plain 为纯文本),第三个参数为编码
    # b = show_weather(get_weather_data())
    # b = '下午好,xx\n' + "".join(b)
    a = jianbao()
    c = a+ '\n' + '\n' + '------------------------------------\n'
    msg = MIMEText(eval('c'), 'plain', 'utf-8')
    # 邮件头信息
    msg['From'] = Header(from_addr)
    msg['To'] = Header(to_addr)
    msg['Subject'] = Header('Never say die.下午好,Maynor')
    # 开启发信服务,这里使用的是加密传输
    server = smtplib.SMTP_SSL(smtp_server)
    server.connect(smtp_server, 465)
    # 登录发信邮箱
    server.login(from_addr, password)
    # 发送邮件
    server.sendmail(from_addr, to_addr, msg.as_string())
    # 关闭服务器
    server.quit()


目录
相关文章
|
10月前
|
存储 算法 调度
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
453 26
|
10月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
623 1
|
10月前
|
机器学习/深度学习 算法 调度
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
432 1
|
9月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
392 100
|
9月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
606 95
|
10月前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
407 104
|
10月前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
696 99
|
10月前
|
IDE 开发工具 开发者
Python类型注解:提升代码可读性与健壮性
Python类型注解:提升代码可读性与健壮性
460 102
|
9月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
520 88
|
9月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。
1528 68

推荐镜像

更多