python結合API實現即時天氣資訊

2022-10-04 22:06:33 字數 1808 閱讀 4155

python結合api實現即時天氣資訊

import urllib.request

import urllib.parse

import json

"""利用「最美天氣」抓取即時天氣情況

snwzsx

"""class zuimei():

def __init__(self):

self.url = 'zuimei/queryweather'

self.headers = {}

self.headers['user-agent'] = 'mozilla/5.0 (wsnwzsxindows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/47.0.2526.80 safari/537.36'

# 部分城市的id資訊

self.cities = {}

self.cities['成都'] ='01012703'

self.cities['杭州'] = '01013401'

self.cities['深圳'] = '01010715'

self.cities['廣州'] = '01010704'

self.cities['上海'] = '01012601'

self.cities['北京'] = '01010101'

# form data

self.data = {}

self.city = '北京'

def query(self,city='北京'):

if city not in self.cities:

print('暫時不支援當前城市')

return

self.city = city

data = urllib.parse.urlencode().encode('utf-8')

req = urllib.request.request(self.url,data,self.headers)

response = urllib.request.urlopen(req)

html = response.read().decode('utf-8')

# 解析json資料並列印結果

self.json_parse(html)

def json_parse(self,html):

target = json.loads(html)

high_te程式設計客棧mp = target['data'][0]['actual']['high']

low_temp = target['data'][0]['actual']['low']

current_temp = target['data'][0]['actual']['tmp']

today_wea = target['data'][0]['actual']['wea']

www.cppcns.com air_desc = target['data程式設計客棧'][0]['actual']['desc']

# 上海 6~-2c 現在溫度 1c 濕度:53 空氣質素不好,注意防霾。

print('%s: %s~%sc 現在溫度 %sc 濕度:%s %s'%(self.city,high_temp,low_temp,current_temp,today_wea,air_desc))

if __name__ == '__main__':

zuimei = zuimei()

zuimei.query('廣州')

效果演示:

本文標題: python結合api實現即時天氣資訊

本文位址:

Python即時網路爬蟲 API說明

1,介面名稱 2,介面說明 如果您想編寫乙個網路爬蟲程式,您會發現大部分時間耗費在調測網頁內容提取規則上,不講正規表示式的語法如何怪異,即便使用xpath,您也得逐個編寫和除錯。如果要從乙個網頁上提取很多字段,逐個除錯xpath將是十分耗時的。通過這個介面,你可以直接獲得乙個調測好的提取器指令碼程式...

ajax php 實現即時聊天

引數設定 顯示 使用者 disonline true 新登陸時顯示最近內容的條數 預設為30條 leastnum 30 預設的房間名 預設是每天換乙個檔案 如果去掉d,則是每月換乙個檔案 room date y m d 房間儲存路徑,必須以 結尾 roomdir rooms 編碼方式 charset...

Python實現Api的Mock測試

前言 什麼是mock?mock簡單的理解就是開發在開發的過程中,需要依賴一部分的介面,但是對方沒有提供或者環境等等情況,總之是沒有,那麼開發使用mock server自己來mock資料,方便自己正常的進行開發和對編寫的功能進行自測。一 搭建json server 開啟cmd輸入npm install...