直接上代码
#!/usr/bin/env Python
#coding=UTF-8
from urllib.request import urlopen
from pyquery import PyQuery as pq
import smtplib
from email.mime.text import MIMEText
import codecs
import time
def sentemail(receiver):
citycode='101020100'#南京代码
url='http://www.weather.com.cn/weather/'+citycode+'.shtml'
html = urlopen(url).read().decode('utf-8')
doc=pq(html)
Today_date=doc('.sky.skyid.lv3.on h1').text()
wea=doc('.sky.skyid.lv3.on p').text()
tem=doc('.sky.skyid.lv3.on.tem i').text()
wind=doc('.sky.skyid.lv3.on .win em span').attr('title')
wind_power=doc('.sky.skyid.lv3.on .win em').text()
light_power=doc('.hide.show .clearfix .li1 span').text()
light_power_way=doc('.hide.show .clearfix .li1 p').text()
feel_index=doc('.hide.show .clearfix .li3.hot span').text()
wear_index=doc('.hide.show .clearfix .li3.hot p').text()
popu_index=doc('.hide.show .clearfix .li6 span').text()
popu_index_2=doc('.hide.show .clearfix .li6 p').text()
tem7d_low=doc('.tem i').text()[4:]
tem7d_high=doc('.tem span').text()
today= time.strftime("%Y-%m-%d",time.localtime(time.time()))
qianyan='<p>'+'地点:上海'+'</p>'+'<p>'+'今天是:'+today+'日,下面奉上今日天气'+'</p>'
jieshuyu='<p>'+'Rush!!!'+'</p>'
body='<p>'+wea+'</p>'+'<p>'+wind+'</p>'+'<p>'+wind_power+'</p>'+'<p>'+'紫外线指数:'+light_power+'</p>'+'<p>'+'紫外线应对:'+light_power_way+'</p>'+'<p>'+'体感:'+feel_index+'</p>'+'<p>'+'穿衣指数:'+wear_index+'</p>'+'<p>'+'空气污染扩散指数:'+popu_index_2+'</p>'+'<p>'+'未来7天温度最高温度:'+tem7d_high+'</p>'+'<p>'+'未来7天温度最低温度:'+tem7d_low+'</p>'
host = 'smtp.163.com'#发件服务器
all=qianyan+body+jieshuyu
port = 465 #发件端口号
sender = 'example@163.com' #发送端的账号
pwd = 'password' #邮件密码,第三方为授权码
msg = MIMEText(all, 'html', 'utf-8')#赋值msg
msg['subject'] = '天气预报' #邮件标题
msg['from'] = sender #显示的发送人
msg['to'] = receiver #显示的收信人
try:
s = smtplib.SMTP_SSL(host, port)
s.login(sender, pwd)
print('yes')
s.sendmail(sender, receiver, msg.as_string())
print ('Done.sent email success')
for i in range(43200):
time.sleep(1)
print(43200-i)
sentemail('example@qq.com')
except smtplib.SMTPException:
print ('Error.sent email fail')
sentemail('example@qq.com')