python網頁爬蟲之天氣查詢

2021-07-09 22:54:28 字數 2112 閱讀 1397

這是用python寫的天氣查詢**,可用。

這裡用的是和風天氣的介面

參考:我用的城市資料:

將城市資料存放本地:

jsons = 

import pickle

pickle_file = open('city_data.pkl', 'wb')

pickle.dump(jsons, pickle_file)

pickle_file.close()

import urllib.request

import json

import pickle

from datetime import date

city1 =

city2 =

num = ''

#城市編碼

defloaddata

(): pickle_file = open('city_data.pkl', 'rb')

global city1

city1 = pickle.load(pickle_file)

definit

(): loaddata()

while

1: flag = 0

p = input('請輸入省:')

for each in city1:

if each['省'] == p:

flag = 1

global city2

city2 = each['市']

break

if flag == 0:

print ('輸入的省不存在!')

continue

else:

while

1: c = input('請輸入城市:')

for each in city2:

if each['市名'] == c:

flag = 0

global num

num = each['編碼']

break

if flag == 1:

print ('輸入的城市不存在!')

continue

else:

return

while

1: init()

url = '' + num + '&key=自己的key值'

data = none

headers =

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

weatherhtml = urllib.request.urlopen(req).read().decode('utf-8')# 讀入開啟的url

fn = str(date.today())+'.txt'

#查詢得到的資料存放本地

weather_file = open(fn, 'w')

weather_file.write(weatherhtml)

weather_file.close()

#print (weatherhtml)

weatherjson = json.loads(weatherhtml)# 建立json

weatherinfo = weatherjson["heweather data service 3.0"]

# 列印資訊

print ('城市:', weatherinfo[0]['basic']['city'])

print ('24小時天氣:')

print ('溫度:', weatherinfo[0]['daily_forecast'][0]['tmp']['max'], '-', weatherinfo[0]['daily_forecast'][0]['tmp']['min'])

print ('天氣:', weatherinfo[0]['daily_forecast'][0]['cond']['txt_d'], ',', weatherinfo[0]['daily_forecast'][0]['cond']['txt_n'])

temp = input ('按任意鍵繼續:')

python爬蟲之墨跡天氣

import requests from lxml.html import etree import json import time 匯入模組 class mojiweather def city name self 定義乙個輸入城市名稱的函式 cityname str input 輸入城市名稱 ...

Python天氣爬蟲

建立beautifulsoup物件 body bs.body 獲取body部分 data body.find div 找到id為7d的div ul data.find ul 獲取ul部分 li ul.find all li 獲取所有的li for day in li 對每個li標籤中的內容進行遍歷 ...

python天氣查詢 python天氣查詢

主要通過字典查詢全國各地主要城市天氣情況 from urllib.request import urlopen from bs4 import beautifulsoup import re citylist main 全國主要城市 北上廣深,華北,東北,華南,西北,西南,華東,華中,def cit...