2020-04-11 Python-pysimplegui-爬蟲(chóng)-天氣查詢系統(tǒng)

1.簡(jiǎn)介

python最常用的gui庫(kù)有三個(gè),分別是tkinter、wxpython和pyqt。這里選用pysimplegui,因?yàn)樗苓m合初學(xué)者,極其容易上手,不過(guò)它在2018年7月發(fā)布的,網(wǎng)上資料幾乎就沒(méi)有,多數(shù)都是從官方文檔翻譯copy過(guò)來(lái)的,所以,你要想掌握它,那最好查閱官方文檔,上面的闡述都很詳細(xì),地址:https://pysimplegui.readthedocs.io/en/latest/,話不多說(shuō),開(kāi)始擼代碼。

2.編程實(shí)現(xiàn)

#!/user/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Mr 雷'

import PySimpleGUI as sg
import requests
import json
import re
from lxml import etree

header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'}
sg.theme('Purple')
label = [[sg.Text('請(qǐng)輸入城市、鄉(xiāng)鎮(zhèn)、街道、景點(diǎn)名稱查詢天氣',size=(33,0)),sg.InputText(size=(20,0))],
         [sg.Button('確認(rèn)',pad=((120,0),20)), sg.Button('退出',pad=((150,0),20))],
         [sg.Text('請(qǐng)選擇查詢區(qū)域')],
         [sg.Listbox(values=['暫無(wú)信息,請(qǐng)輸入關(guān)鍵城市進(jìn)行顯示'],size=(58,10),key='box',enable_events=True)]]
win1 = sg.Window('天氣查詢',label)
win2_active=False

def submit(city,id):
    weather_data = get_weather(id)
    frame_layout =[]
    for i in range(len(weather_data)):
        if len(weather_data[0]) == 6:
            frame_layout.append([[sg.Text('天氣:' + weather_data[i][1])],
                                 [sg.Text('最高氣溫:' + weather_data[i][2])],
                                 [sg.Text('最低氣溫:' + weather_data[i][3])],
                                 [sg.Text('風(fēng)向:' + weather_data[i][4])],
                                 [sg.Text('風(fēng)級(jí):' + weather_data[i][5])]])
        else:
            frame_layout.append([[sg.Text('天氣:' + weather_data[i][1])],
                                 [sg.Text('風(fēng)向:' + weather_data[i][2])],
                                 [sg.Text('風(fēng)級(jí):' + weather_data[i][3])]])
    layout = [[sg.Text('一周天氣狀況',justification='center')],
              [sg.Frame(weather_data[0][0],frame_layout[0]),
              sg.Frame(weather_data[1][0],frame_layout[1]),
              sg.Frame(weather_data[2][0],frame_layout[2]),
              sg.Frame(weather_data[3][0],frame_layout[3]),
              sg.Frame(weather_data[4][0],frame_layout[4]),
              sg.Frame(weather_data[5][0],frame_layout[5]),
              sg.Frame(weather_data[6][0],frame_layout[6])]]
    win2 = sg.Window(f'{city}天氣預(yù)報(bào)', layout)
    return win2

def get_city(name):
    r = requests.get('http://toy1.weather.com.cn/search?cityname={}'.format(name),headers=header)
    r.encoding = r.apparent_encoding
    text = r.text.replace('(', '').replace(')', '')
    infos = json.loads(text)
    citys = []
    info_dict = {}
    for info in infos:
        id = info['ref'].split('~')[0]
        info = list(''.join(re.findall('[\u4e00-\u9fa5]', info['ref'])))
        new_info = []
        for i in info:
            if i not in new_info:
                new_info.append(i)
        new_info = ''.join(new_info)
        citys.append(new_info)
        info_dict[new_info] = id
    return citys,info_dict

def get_weather(id):
    data = []
    url1 = f'http://www.weather.com.cn/weather/{id}.shtml'
    url2 = f'http://forecast.weather.com.cn/town/weathern/{id}.shtml'
    r = requests.get(url1,headers=header)
    if r.text != '<!-- empty -->':
        r.encoding = r.apparent_encoding
        html = etree.HTML(r.text)
        elements = html.xpath('//ul[@class="t clearfix"]/li')
        for element in elements:
            date = element.xpath('./h1/text()')[0]
            weather = element.xpath('./p[@class="wea"]/text()')[0]
            max_tem = element.xpath('./p[@class="tem"]/span/text()')[0]+'℃'
            min_tem = element.xpath('./p[@class="tem"]/i/text()')[0]
            wind_direction = '、'.join(element.xpath('./p[@class="win"]/em/span/@title'))
            wind_scale = element.xpath('./p[@class="win"]/i/text()')[0]
            data.append([date,weather,max_tem,min_tem,wind_direction,wind_scale])
    else:
        r = requests.get(url2, headers=header)
        r.encoding = r.apparent_encoding
        html = etree.HTML(r.text)
        elements = html.xpath('//ul[@class="blue-container backccc"]/li')
        data_elements = html.xpath('//ul[@class="date-container"]/li')
        for i in range(1,len(elements)-1):
            date = ' '.join(data_elements[i].xpath('./p/text()'))
            weather = elements[i].xpath('./p[@class="weather-info"]/text()')[0].strip()
            wind_direction = '、'.join(elements[i].xpath('./div[@class="wind-container"]/i/@title'))
            wind_scale = elements[i].xpath('./p[@class="wind-info"]/text()')[0].strip()
            data.append([date, weather, wind_direction, wind_scale])
    return data

while True:
    event1,value1 = win1.read()
    if event1 in (None,'退出'):
        break
    if event1 == '確認(rèn)':
        city,info = get_city(value1[0])
        win1['box'].update(city)
        value1['box'] = False
    if value1['box'] and not win2_active:
        if value1['box'][0] in info.keys():
            id = info[value1['box'][0]]
            win2_active = True
            win1.Hide()
            win2 = submit(value1[0],id)
            while True:
                event2, value2 = win2.read()
                if event2 is None:
                    win2.close()
                    win2_active = False
                    win1.UnHide()
                    break

3.創(chuàng)建Windows .exe文件

在Windows命令提示符下輸入以下命令:

pyinstaller -wF 天氣查詢.py

4.效果展示

查詢搜索.png

天氣預(yù)報(bào).png

5.結(jié)語(yǔ)

通過(guò)這個(gè)項(xiàng)目實(shí)現(xiàn)了簡(jiǎn)單的桌面應(yīng)用軟件,對(duì)于顏值要求不那么多,想做出東西的,方便給用戶展示的,可以嘗試pysimplegui,實(shí)際上tkinter也是可以的。如果想從事gui的,還是不用考慮python了吧,c#都比這強(qiáng)。此文未經(jīng)作者許可禁止轉(zhuǎn)載。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容