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

完成

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值