欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

Python-爬取中国天气网天气并通过邮箱定时发送

发布时间:2025/3/21 python 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Python-爬取中国天气网天气并通过邮箱定时发送 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

获取天气信息脚本如下,

#!/usr/bin/python3 # -*- coding: utf-8 -*- import re import requests from bs4 import BeautifulSoup import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')r = requests.get('http://www.weather.com.cn/weather/101120301.shtml',timeout = 30) r.raise_for_status() r.encoding = 'utf-8'rdata = re.findall(r'<h1>.*?</h1>',r.text) rwea = re.findall(r'\"wea\">.*?</p>',r.text) rtemp1 = re.findall(r'\/<i>.*?</i>',r.text) rtemp2 = re.findall(r'<span>\d+\.?\d*</span>',r.text) for i in range(6):data = rdata[i].split('>')[1].split('<')[0]wea = rwea[i].split('>')[1].split('<')[0]temp1 = rtemp1[i].split('>')[1].split('<')[0]temp2 = rtemp2[i].split('>')[1].split('<')[0]# temp2 = rtemp2[i].split('>')[1].split('<')[0]# tplt = "{0:^10}\t{1:{6}^10}\t{2:}\t{3:<}\t{4:}\t{5:}" tplt = "{0:^10}\t{1:{4}^10}\t{2:}\t{3:<}\t{4:}" print(tplt.format(data,wea,temp1,"~" + temp2 ,chr(12288)))

保存为crawlChineseWeather.py,将其上传服务器,然后安装脚本所需要的库

sudo apt install python3-pip sudo apt-get install python3-bs4

然后在服务器中安装mail服务
Centos7默认安装了mail
Ubuntu16.04运行如下命令安装

sudo apt install mailutils

添加一个定时任务,每天7:00am发送天气信息到给定邮箱

0 7 * * * python3 crawlChineseWeather.py | mail -s subject email-Address

完成

总结

以上是生活随笔为你收集整理的Python-爬取中国天气网天气并通过邮箱定时发送的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。