資源簡介
這是python版的天氣預報。
使用須知:
使用前請pip安裝requests和BeautifulSoup庫!
原理:
利用爬蟲獲取天氣信息
解碼
gui顯示
默認為北京的天氣,可在代碼第七行改!
#可以看看我的其他資源鴨!
代碼片段和文件信息
import?requests
from?bs4?import?BeautifulSoup
from?tkinter?import?*
import?datetime
requests.session()
r?=?requests.get(‘http://wthrcdn.etouch.cn/WeatherApi?city=北京‘)
soup?=?BeautifulSoup(r.text‘lxml‘)
a?=?soup.find_all(‘city‘)
city?=?a[0].get_text()
print(a[0].get_text())
a?=?soup.find_all(‘wendu‘)
wendu?=?a[0].get_text()
print(‘溫度為:‘a[0].get_text())
a?=?soup.find_all(‘shidu‘)
shidu?=?a[0].get_text()
print(‘濕度為:‘a[0].get_text())
a?=?soup.find_all(‘fengli‘)
fengli?=?a[0].get_text()
print(‘風力:‘a[0].get_text())
a?=?soup.find_all(‘fengxiang‘)
fengxiang?=?a[0].get_text()
print(‘風向:‘a[0].get_text())
a?=?soup.find_all(‘quality‘)
quality?=?a[0].get_text()
print(‘空氣質量:‘a[0].get_text())
a?=?soup.find_all(‘pm25‘)
pm25?=?a[0].get_text()
print(‘PM2.5:‘a[0].get_text())
date_time?=?datetime.datetime.now().strftime(‘%Y_%m_%d‘)
filename?=?date_time?+‘.txt‘
with?open(filename‘w‘encoding=‘utf8‘)?as?f:
????f.write(‘城市:‘+city?+‘\n‘)
????f.write(‘溫度:‘+wendu?+‘\n‘)
????f.write(‘濕度:‘+str(shidu)?+‘\n‘)
????f.write(‘風力:‘+?fengli?+‘\n‘
評論
共有 條評論