API爬取天⽓预报数据
API爬取天⽓预报数据
"""
该⽹站为个⼈开发者提供免费的天⽓预报数据,⾃⾏访问官⽹注册,在控制台看到个⼈的key。
然后看API⽂档,基本可以开发了,有访问次数限制。
"""
爬取数据代码
import requests
import time
import pymongo
"""
和风天⽓API提供了3000多个城市的天⽓预报,我们先获取这些城市的cid,
再循环获取3000个城市的天⽓预报,
存⼊mongodb
"""
#建⽴mongodb的连接
client=pymongo.MongoClient(host="localhost",port=27017)
#建⽴数据库weather
book_weather=client['weather']
#在weather数据库中建⽴集合:sheet_collection_1
sheet_weather=book_weather['sheet_collection_1']
1:获取⽹站给我们提供的天⽓预报csv⽂件。
#获取city的cid 地区/城市ID CN101080402
#:获取城市列表的url
url="a.hecdn/download/dev/china-city-list.csv"
#请求ulr
(url)
#返回字符串内容,csv格式
# print(data)
#转为列表天气预报代码大全
data1=data.split('\r')
#去除前两⾏标题头
for i in range(2):
for item in data1:
# print(item[0:12])
2:调⽤接⼝获取数据
weather_url='free-api.heweather/s6/weather/now?location='+item[0:12].strip()+'&key=13e99fe03be0440cb9ff12e2edfe1ab6'    # print(weather_url)
weather_(weather_url)
ding="utf-8"
time.sleep(2)
# print()
dic=weather_html.json()
3:通过在线json解析⼯具,到我们需要的数据,再插⼊到mongodb中
city=dic["HeWeather6"][0]["basic"]["location"]
twt=dic["HeWeather6"][0]["now"]["tmp"]
ws=dic["HeWeather6"][0]["now"]["cond_txt"]
w_date=dic["HeWeather6"][0]["update"]["loc"]
#插⼊数据到mongodb中
sheet_weather.insert_one({"城市":city,"⽓温":twt,"天⽓情况":ws,"天⽓⽇期":w_date})    print("城市代码:{0}".format(item[0:12].strip()))
4调试能获取到想要的数据之后,
传到linux系统中运⾏
ubuntu@ubuntu:~$ rz -y
rz waiting to receive.
Starting zmodem transfer.  Press Ctrl+C to cancel.
Transferring pymongo-3.10.1-cp37-cp37m-manylinux2014_x86_
100%    451 KB    451 KB/sec    00:00:01      0 Errors
#安装pymongo
ubuntu@ubuntu:~$ pip3 install pymongo-3.10.1-cp37-cp37m-manylinux2014_x86_64.whl Defaulting to user installation because normal site-packages is not writeable Processing ./pymongo-3.10.1-cp37-cp37m-manylinux2014_x86_64.whl
Installing collected packages: pymongo
Successfully installed pymongo-3.10.1
#运⾏
ubuntu@ubuntu:~$ nohup python get_city.py &
[1] 12938
ubuntu@ubuntu:~$ nohup: ignoring input and appending output to 'nohup.out'
#查看,输出
ubuntu@ubuntu:~$ tail -f nohup.out
城市代码:CN101010100
城市代码:CN101010200
城市代码:CN101010300
城市代码:CN101010400
城市代码:CN101010500
城市代码:CN101010600