一。首先我们来确定我们要完成这个目标需要做的事情:
1.得到sys.argv中的位置信息。
2.通过requests.get()函数来下载相应内容。
3.将得到的Json数据用json.loads()函数将Json格式的数据转换为Python数据格式。
4.将得到的数据打印出来。
二。完成相应代码块。
1.得到sys.argv中的位置信息。
import json,sys,requests
#1.get the location command from sys.arge
if len(sys.argv) < 2:
print('Usage:quickWeather.py location')
sys.exit()
location = ' ' .join(sys.argv[1:])
引入需要的模块,sys.argv命令行中若没有相关信息则退出并打印出使用方法。若有参数则将该参数用空格来分割。
2.通过requests.get()函数来下载相应内容。
#2.get the weather situation from the web by request.get()
url = 'http://api.openweathermap.org/data/2.5/weather?q=%s&appid=***YOUR API KEY***' %(location)
response = requests.get(url)
response.raise_for_status()
利用得到的位置消息来得到相应的url,然后使用resquests.get()函数来下载信息,并且使用raise_for_status()来检查是否发生错误。
3.将得到的Json数据用json.loads()函数将Json格式的数据转换为Python数据格式。
#3.transfor the Json data to the Python data by json.loads()
weatherData = json.loads(response.text)
下载到的信息赋值给了respond,然后将respond中的text文本转化为Python数据格式。
4.将得到的数据打印出来。
#4.print the weather situation
w = weatherData['weather']
print('Current weather in %s :' % (location))
print(w[0]['main'],'-',w[0]['description'])
三。运行并显示结果。
将写好的文件保存然后在cmd中到文件所在的根目录运行此文件。即可得到结果。
注意:需要在后面指出的想要了解的城市的名称。
四。需要注意的内容。
1.有关sys.argv[]
sys.argv[]可以使得程序从外部来获取数据,但是通常我们从外部获取的数据是多个的,且多个数据之间通过空格开进行分割。
所以sys.argv[]可以看作一个列表,列表中的第一个元素sys.argv[0]代表文件本身的路径,所以从sys.argv[1]开始才是从外界获取的参数。
2.有关url
我这里使用的是一个外网,你可以使用一些内网来进行。如果不确定是否可以的时候,可以在浏览器中输入你写的url来看是否可以出现Json数据:
如果不能出现,请重新修改你的url。
3.关于使用OpenWeatherMap网站
使用这个网站是要注意需要加入APPID,否则会出现401错误,这就需要你先在官网注册一个账号(同样需要外网才能注册成功,否则会出现验证失败(recaptcha verification failed,please try again.)的问题。注册成功后在首页中右上角自己的用户名下找到“My API Keys”
进去就会找到自己的API Key。
然后将自己的API加在自己的url的相应位置
url = 'http://api.openweathermap.org/data/2.5/weather?q=%s&appid=***YOUR API KEY***' %(location)
即可成功访问此网站并得到数据。