Python 获取全国所有城市实时天气预报


查询所有天气数据并打印在控制台:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import requests
import time

# 首先获取全国城市列表
url = 'https://a.hecdn.net/download/dev/china-city-list.csv'
strhtml = requests.get(url)
data = strhtml.text
datal = data.split("\n")
# 列表的前三行是我们不需要的,删除
for i in range(3):
datal.remove(datal[0])
# 根据城市编码获取实时天气预报
for item in datal:
url = 'https://free-api.heweather.net/s6/weather/now?location=' + item[0:11] +'&key=xxx'
strhtml=requests.get(url)
time.sleep(1)
print(strhtml.text)

其中用到了 和风天气 的 API,免费用户有流量限制。代码中的 key 需要换成你自己的 key。

将获取到的天气数据保存在 mongodb 数据库中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests
import time
import pymongo

# 建立连接
client = pymongo.MongoClient('192.168.1.123',27000)
# 创建数据库
book_weather=client['weather']
# 创建表
sheet_weather=book_weather['sheet_weather_3']
url = 'https://a.hecdn.net/download/dev/china-city-list.csv'
strhtml = requests.get(url)
data = strhtml.text
datal = data.split("\n")
for i in range(3):
datal.remove(datal[0])
for item in datal:
url = 'https://free-api.heweather.net/s6/weather/now?location=' + item[0:11] +'&key=xxx'
strhtml=requests.get(url)
time.sleep(1)
dic = strhtml.json()
# 向数据库中写入数据
sheet_weather.insert_one(dic)

查询北京的天气数据:

1
2
3
4
5
6
7
import pymongo

client = pymongo.MongoClient('192.168.1.123',27000)
book_weather = client['weather']
sheet_weather = book_weather['sheet_weather_3']
for i in sheet_weather.find({'HeWwather6.basic.city':'北京'}):
print(i)

参考文档:
Python 3爬虫、数据清洗与可视化实战