[qiqiqiaoyi] series - Python!! The weather forecast will be sent to QQ email at 8:00 every morning

SunriseCai 2020-11-13 11:31:54
qiqiqiaoyi series python weather forecast


This blog is only for my spare time to record articles , Publish to , Only for users to read , If there is any infringement , Please let me know , I'll delete it .

Add

Quite a few Little whore The message said this article of no avail , Because the weather forecast can be received directly by turning on the mobile phone , Why do you want to send it to your email !!! Then I can only say : Because you're useless , So you're useless !!!

ps: In fact, some of them are reasonable , I think it's troublesome to check the weather forecast , So it's not too much trouble checking email ? Ha ha ha

The main introduction here is Ideas , It's not the weather forecast ! It's not the weather forecast !! It's not the weather forecast !!! The weather forecast is just for example . Please don't be so rigid !!!

Here are two scenarios I'll use :

  1. Send the sorted documents to the leader's mailbox before work on weekdays .( Put the document in the specified folder , Traverse and send )
  2. Server logs in the morning 8 Click to send it to my email , On the way to work and commute, you can take a look at the server the night before yesterday .
  3. I'll add some useful scenes later ...

The following has not been changed , Consistent with the initial post .


Preface :

It's getting cooler recently , I will check the weather every day when I get up . But I find it troublesome to check the weather , So the idea of automatically getting the weather forecast every day and sending it to your personal mailbox .

If you find it troublesome to check the weather , Look at this article .
And this article !! Will explain in detail how to achieve daily 8:00 am will be the latest 7 The weather condition will be sent to your personal email .
There are four steps to automatically send weather conditions to your personal email address .

1. Sign up for free weather API

1.1 Open the registration account of Hefeng weather

1. The picture below is Wind weather :https://dev.heweather.com/ Home page , Open the registration .
 Insert picture description here
2. After the account is registered successfully, click New application , Create a Key, This Key It's for carrying on Wind weather API Called .
You can see that after the new building is successful Key It's a long string , This is the key to get weather information .
 Insert picture description here

1.2 Turn on the weather API Interface specification , Take a look at the development documentation for windy weather .

API Developing documents , Click to jump to .
 Insert picture description here
As you can see from the above figure ( There are commercial version and free version. I use free version here ), There are many kinds of weather-type, Here we use forecast, This is to get 3-10 Weather forecast .

According to the above request URL The example shows that , We need to call url by

https://free-api.heweather.net/s6/weather/forecast?location= City Code &key= self-created Key

2. Write code to get weather

City can fill in Chinese , You can also fill in City Code City code query .

2.1 Get the weather forecast

import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxxxxx'
res = requests.get(url)
print(res.text)

The return is json File format , You can see that it returns from the beginning of the query day 7 Weather forecast information .
 Insert picture description here
The next task is to analyze this pile of json Format data .

2.2 City longitude and latitude information query

import json
import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxxxxx'
res = requests.get(url).json() # Because the return is json Format file
result = res['HeWeather6'][0]['basic']
print(result)
# This is the longitude and latitude of the city in question , Time zone and so on .
## {
'cid': 'CN101280101', 'location': ' Guangzhou ', 'parent_city': ' Guangzhou ', 'admin_area': ' guangdong ', 'cnty': ' China ', 'lat': '23.12517738', 'lon': '113.28063965', 'tz': '+8.00'}

2.3 Check the future of your city 7 Sky information

import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxxxxx'
res = requests.get(url).json() # The data returned is json Format
result = res['HeWeather6'][0]['daily_forecast']
print(result)

Because it's called here API Returns the 7 Days of data , So it will return 7 Group the data below .

 {

"cond_code_d": "100", # Weather conditions during the day 100 For the sake of clearing 101 For cloudy 104 For Yin etc.
"cond_code_n": "100", # Night weather conditions
"cond_txt_d": " Fine ", # Description of weather conditions during the day
"cond_txt_n": " Fine ", # Description of weather conditions at night
"date": "2019-11-10", # Forecast date
"hum": "50", # Relative humidity
"mr": "16:33", # Monthly rise time
"ms": "04:21", # The setting of the moon
"pcpn": "0.0", # precipitation
"pop": "0", # Probability of precipitation
"pres": "1013", # Atmospheric pressure
"sr": "06:37", # Sunrise time
"ss": "17:43", # Sunset time
"tmp_max": "27", # maximum temperature
"tmp_min": "16", # Minimum temperature
"uv_index": "7", # UV intensity index
"vis": "25", # visibility , Company : km
"wind_deg": "-1", # wind direction 360 angle
"wind_dir": " No sustained wind direction ", # wind direction
"wind_sc": "1-2", # wind
"wind_spd": "6" # The wind speed , km / Hours
}
......

2.4 Get the weather information you need

import csv
import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxx'
res = requests.get(url).json()
result = res['HeWeather6'][0]['daily_forecast']
location = res['HeWeather6'][0]['basic']
city = location['parent_city']+location['location']
names = [' City ',' Time ',' weather condition ',' Maximum temperature ',' Minimum temperature ',' sunrise ',' Sunset ']
for data in result:
date = data['date']
cond = data['cond_txt_d']
max = data['tmp_max']
min = data['tmp_min']
sr = data['sr']
ss = data['ss']
print(city,date,cond,max,min,sr,ss)
## Returned data
Guangzhou, Guangzhou 2019-11-10 Fine 27 16 06:37 17:43
Guangzhou, Guangzhou 2019-11-11 Fine 28 18 06:38 17:43
Guangzhou, Guangzhou 2019-11-12 Fine 29 18 06:39 17:42
Guangzhou, Guangzhou 2019-11-13 cloudy 28 17 06:39 17:42
Guangzhou, Guangzhou 2019-11-14 Fine 25 15 06:40 17:42
Guangzhou, Guangzhou 2019-11-15 Fine 26 15 06:40 17:42
Guangzhou, Guangzhou 2019-11-16 Fine 27 16 06:41 17:41

3. Write code to send email

Reference here Novice tutorial Of Python SMTP Send E-mail
1. First go QQ mailbox
open Set up - Account - Opening service - Turn on POP3/SMTP service , And then click Generate authorization code ,python To send mail, you need to use .
 Insert picture description here
Go straight to the code , Don't explain .

# Simple mail transfer protocol
import smtplib
import email
import time
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Set the domain name of the mailbox
HOST = 'smtp.qq.com'
# Set the subject line
SUBJECT = ' Today's weather forecast has arrived , Master '
# Set the sender's mailbox
FROM = 'xxx@qq.com'
# Set up the recipient mailbox
TO = 'xxx@163.com,xxx@qq.com' # You can fill in more than one mailbox , Separate with commas , I'll use it later split Do the comma division
message = MIMEMultipart('related')
# -------------------------------------- Send text -----------------
# Send the email body to the other party's mailbox
message_html = MIMEText(" Master, your email has arrived \n\nThis is test", 'plain', 'utf-8') # \n For newline
message.attach(message_html)
# ------------------------------------- Add files ---------------------
# Make sure that the current directory has test.csv This file
message_xlsx = MIMEText(open('test.csv', 'rb').read(), 'base64', 'utf-8')
# Set the name of the file in the attachment
message_xlsx['Content-Disposition'] = 'attachment;filename="test01.csv"'
message.attach(message_xlsx)
# Set the email sender
message['From'] = FROM
# Set up mail recipients
message['To'] = TO
# Set the subject line
message['Subject'] = SUBJECT
# Get a certificate for the Simple Mail Transfer Protocol
email_client = smtplib.SMTP_SSL()
# Set the domain name and port of the sender's mailbox , Port is 465
email_client.connect(HOST, '465')
# --------------------------- Email authorization code ------------------------------
result = email_client.login(FROM, ' Your authorization code ')
print(' Login results ', result)
email_client.sendmail(from_addr=FROM, to_addrs=TO.split(','), msg=message.as_string())
# Turn off the email sending client
email_client.close()

4. Complete code

# coding=gbk ## notes :linux This line is not needed on the server ,window need
import csv
import time
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
url = r'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxx'
# Get the time of the day 2019-11-10
today_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
def get_weather_data():
res = requests.get(url).json()
# res.encoding = 'utf-8'
result = res['HeWeather6'][0]['daily_forecast']
location = res['HeWeather6'][0]['basic']
city = location['parent_city'] + location['location']
names = [' City ', ' Time ', ' weather condition ', ' Maximum temperature ', ' Minimum temperature ', ' sunrise ', ' Sunset ']
with open('today_weather.csv', 'w', newline='')as f:
writer = csv.writer(f)
writer.writerow(names)
for data in result:
date = data['date']
cond = data['cond_txt_d']
max = data['tmp_max']
min = data['tmp_min']
sr = data['sr']
ss = data['ss']
writer.writerows([(city, date, cond, max, min, sr, ss)])
send_email()
def send_email():
# Set the domain name of the mailbox
HOST = 'smtp.qq.com'
# Set the subject line
SUBJECT = '%s Daily weather forecast information , Enclosed please find '%today_time
# Set the sender's mailbox
FROM = 'xxx@qq.com'
# Set up the recipient mailbox
TO = 'xxx@163.com,xxx@qq.com' # It can be sent to multiple email addresses at the same time
message = MIMEMultipart('related')
# -------------------------------------- Send text -----------------
# Send the email body to the other party's mailbox
message_html = MIMEText("%s The daily weather forecast has arrived , Enclosed please find " % today_time, 'plain', 'utf-8')
message.attach(message_html)
# ------------------------------------- Add files ---------------------
# today_weather.csv This file
message_xlsx = MIMEText(open('today_weather.csv', 'rb').read(), 'base64', 'utf-8')
# Set the name of the file in the attachment
message_xlsx['Content-Disposition'] = 'attachment;filename="today_weather.csv"'
message.attach(message_xlsx)
# Set the email sender
message['From'] = FROM
# Set up mail recipients
message['To'] = TO
# Set the subject line
message['Subject'] = SUBJECT
# Get a certificate for the Simple Mail Transfer Protocol
email_client = smtplib.SMTP_SSL(host='smtp.qq.com')
# Set the domain name and port of the sender's mailbox , Port is 465
email_client.connect(HOST, '465')
# --------------------------- Email authorization code ------------------------------
result = email_client.login(FROM, ' Your authorization code ')
print(' Login results ', result)
email_client.sendmail(from_addr=FROM, to_addrs=TO.split(','), msg=message.as_string())
# Turn off the email sending client
email_client.close()
get_weather_data()

5. Deploy code to the server , To run code on time every day

It's called code deployment , In other words, copy the code to the server , Then let the code run .
Here we'll use a toss and throw linux Knowledge .

5.1 First copy the file to the server

This is an easy step , Copy and paste directly .

5.2 nothing

Create a sum python Files in the same folder startup.sh file ( Name at will ), And then in startup.sh Fill in the document with

python3 ./python File name # Remember / There's a little bit ahead .

 Insert picture description here
And then again /etc/crontab Fill in stratup.sh The path of the file can be .
 Insert picture description here
Now that you've learned to send the weather forecast , How about sending a voice or short video every day ? , With customized loliyin , Yu Jie Yin sends the voice of weather forecast information to the other party or attaches a short video , Beauty is not true ?? Click the link below to jump to , Study diy Voice and how to get short video .

  • diy Customize your own text to voice
  • Get tiktok short video

Click through :【 It's a wonderful trick 】 series -Python Realization Voice to text ?? no !! It's text to speech ,DIY The loliyin you want !!!
Click through : Super simple !!! utilize python Download some audio and video without watermark

above , You can do it with your hands , Every day 8 I got the latest weather forecast on time .
If you're too lazy to do it , You can try to leave your mailbox + City I won't do it for you anyway
This sharing is here . If you have any questions, please leave a message below .

版权声明
本文为[SunriseCai]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database