背景
学妹因为淋雨成了落汤鸡,发了个朋友圈感慨一下啊,然后......
夜深人静之时,我连夜用Python写了一个天气预报(如下图):
首先安装request库
pip install requests
现在,我们需要将包导入到我们的 python 脚本中。使用以下命令执行此操作。
import requests
让我们要求用户输入她希望获取天气详细信息的城市名称。
city = input('input the city name')
print(city)
如果您只检查自己,您也可以对值进行硬编码。
city = 'bhopal'
现在,让我们显示一条简单的消息。
print('Displaying Weather report for: ' + city)
#output:
Displaying Weather report for: bhopal
让我们定义 URL,我们将在这里使用format
城市作为参数传递。
url = 'https://wttr.in/{}'.format(city)
我们得到的数据存储在res
. 我们将使用该text
方法来提取我们想要的天气详细信息并让我们显示结果。
print(res.text)
完整代码:
'''
Weather forecast with Python
By: 程序员启航
'''
#import the necessary package!
import requests
city = input('请输入城市:')
print(city)
# or you can also hard-code the value
# city = 'bhopal'
#Display the message!
print('显示天气报告: ' + city)
#fetch the weater details
url = 'https://wttr.in/{}'.format(city)
res = requests.get(url)
#display the result!
print(res.text)
*如果你用得到的话可以直接拿走,在我的QQ技术交流群里,可以自助拿走,群号是605018913