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'

.*?

'
,r.text) rwea = re.findall(r'\"wea\">.*?

'
,r.text) rtemp1 = re.findall(r'\/.*?',r.text) rtemp2 = re.findall(r'\d+\.?\d*',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网络爬虫)