使用Python抓取当地天气状况

Python抓取天气状况,运用官方的天气API,可以获取实时的天气信息。


使用Python抓取当地天气状况,使用的Python3.6。主要用到了字符型str的split方法,用来分割soup网页信息,最后形成一条信息。

天气信息网页:http://www.weather.com.cn/weather1d/101270101.shtml

代码实现如下:


# __auther__= Henry
import requests
from bs4 import BeautifulSoup
import time
 
def get_weather_info( City_Id):
# @param
# City_Id---->Weather_Info
# City_Id is as follows, City_Id = 101270101, standing for Chengdu
# http://www.weather.com.cn/weather1d/101270101.shtml
nickname = "Henry"
UA = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.13 Safari/537.36"
if(City_Id == None): # judge entrance param
url = 'http://www.weather.com.cn/weather1d/101270101.shtml' #三亚101310201
else:
City_Id = str(City_Id)
url = "http://www.weather.com.cn/weather1d/" + City_Id + ".shtml"
 
header = {"User-Agent": UA,
"Referer": "http://zuoxueba.org/"
}
 
session = requests.get(url,header)
soup = BeautifulSoup(session.content, 'html.parser')
# @global param
# @ tim
# @ city_name
# @ AQI
# @ max_tem, min_tem
 
# tim的格式
# 2018 - 11 - 24 12: 02, Sat.
w_0 = time.strftime('%w', time.localtime(time.time()))
w=['Mon.','Tue,','Weds.','Thur.','Fri.','Sat.','Sun.']
week = w[(int(w_0)-1)]
tim = time.strftime('%Y-%m-%d', time.localtime(time.time())) + ", " +week
# print(tim)
 
# 从title中拆分出城市名字
city_name = str(soup.title).split("【", 1)[1].split("】", 1)
city_name = city_name[0]
 
# 从“ p class = sun sunDown ”中 拆分出日落时间
sun_fall_time = soup.find_all('p', 'sun sunDown')
sun_fall_time = str(sun_fall_time).split('<span>',1)[1].split('</span>',1)[0]
 
# AQI cannot capture js content. TODO
# AQI = soup.find_all('p','weatherChart')
# print(str(AQI))
# AQI = str(AQI).split('<span>', 1)[1].split('</span>', 1)[0]
 
# 白天最低最高温度
# tem = soup.find_all('input', 'hidden_title')
# print(str(tem))
# tem = soup.find_all('input', 'hidden_title')
peak_tem = soup.find_all('p', 'tem')
max_tem = str(peak_tem).split('<span>',3)[1].split('</span>',1)[0]+"℃"
min_tem = str(peak_tem).split('<span>', 3)[2].split('</span>', 1)[0] + "℃"
# 晴/小雨/小雨转晴
status = soup.find_all('p','wea')
status = str(status).split('" ',4)[1].split('"',3)[1]
 
content = nickname + ",早上好呀!这是" + tim + "的" + city_name + "," + status + ",白天最高" + \
max_tem + ",夜晚最低" + min_tem + ',天冷了,不要着凉哈' +',Have a nice day~'
print(sms_content)# return content
 
if __name__ == "__main__":
get_weather_info(101270101)
# 101270101是成都的编号,使用时改成自己所在的城市编号(网页url中获取)

最后接入短信api,定时任务,每天给我短信天气预报,美滋滋。