python實現定時顯示天氣預報信息


from datetime import datetime
import json
import requests
import urllib.request # 需要安裝 urllib 庫
from bs4 import BeautifulSoup # 需要安裝 bs4 庫
import os
from apscheduler.schedulers.blocking import BlockingScheduler


def get_iciba_everyday_chicken_soup():
url = 'http://open.iciba.com/dsapi/'
r = requests.get(url)
all_content = json.loads(r.text) # 獲取到json格式的內容,內容很多,json.loads: 將str轉成dict
English = all_content['content'] # 提取json中的英文雞湯
Chinese = all_content['note'] # 提取json中的中文雞湯
everyday_soup = English + '\n' + Chinese # 合並需要的字符串內容
return everyday_soup # 返回結果


# print(get_iciba_everyday_chicken_soup())


def get_weather(city_pinyin):
# 聲明請求頭,模擬真人操作,防止被反爬蟲發現
#header需要F12抓取下信息
header = {
"User-Agent": "*******"}
# 通過傳入的城市名拼音參數來拼接出該城市的天氣預報的網頁地址
#city_pinyin='zhengzhou'
website = "https://www.tianqi.com/" + city_pinyin + "/"
req = urllib.request.Request(url=website, headers=header)
page = urllib.request.urlopen(req)
html = page.read()
soup = BeautifulSoup(html.decode("utf-8"), "html.parser")
# html.parser表示解析使用的解析器
nodes = soup.find_all('dd')
tody_weather = [node.text.strip() for node in nodes] # 定義一個列表,並遍歷nodes
tody_weather[0] = tody_weather[0][:2] # 去除多余字符
# 去除字符串中的空行:
tianqi = " ".join([s for s in tody_weather if s.strip("\n")])
print(tianqi)
return tianqi
# 返回結果


# 調用封裝號好的函數獲取天氣預報,參數‘zhengzhou’是鄭州的拼音:
# print(get_weather("zhengzhou"))


if __name__ == '__main__':
scheduler = BlockingScheduler(timezone="Asia/Shanghai")
scheduler.add_job(get_weather, 'interval', seconds=3,args=['zhengzhou'])
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C '))
try:
scheduler.start()
except(KeyboardInterrupt, SystemExit):
pass



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM