1. 程式人生 > 實用技巧 >Python 爬蟲+tkinter介面 實現歷史天氣查詢

Python 爬蟲+tkinter介面 實現歷史天氣查詢

文章目錄

一、實現效果

很多人學習python,不知道從何學起。
很多人學習python,掌握了基本語法過後,不知道在哪裡尋找案例上手。
很多已經做案例的人,卻不知道如何去學習更加高深的知識。
那麼針對這三類人,我給大家提供一個好的學習平臺,免費領取視訊教程,電子書籍,以及課程的原始碼!
QQ群:101677771

1. python程式碼

import requests
from lxml import etree
import re
import tkinter as tk
from PIL import Image, ImageTk
from xpinyin import Pinyin


def get_image(file_nam, width, height):
    im = Image.open(file_nam).resize((width, height))
    return ImageTk.PhotoImage(im)


def spider():
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
        "referer": "https://lishi.tianqi.com/chengdu/index.html"
    }
    p = Pinyin()
    place = ''.join(p.get_pinyin(b1.get()).split('-'))           # 獲取地區文字框的輸入  變為拼音
    # 處理使用者輸入的時間
    # 規定三種格式都可以 2018/10/1  2018年10月1日  2018-10-1
    date = b2.get()   # 獲取時間文字框的輸入
    if '/' in date:
        tm_list = date.split('/')
    elif '-' in date:
        tm_list = date.split('-')
    else:
        tm_list = re.findall(r'\d+', date)

    if int(tm_list[1]) < 10:       # 1-9月  前面加 0
        tm_list[1] = f'0{tm_list[1]}'
    # 分析網頁規律  構造url
    # 直接訪問有該月所有天氣資訊的頁面 提高查詢效率
    url = f"https://lishi.tianqi.com/{place}/{''.join(tm_list[:2])}.html"
    resp = requests.get(url, headers=headers)
    html = etree.HTML(resp.text)
    # xpath定位提取該日天氣資訊
    info = html.xpath(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')
    # 輸出資訊格式化一下
    info1 = ['日期:', '最高氣溫:', '最低氣溫:', '天氣:', '風向:']
    datas = [i + j for i, j in zip(info1, info)]
    info = '\n'.join(datas)
    t.insert('insert', '        查詢結果如下        \n\n')
    t.insert('insert', info)
    print(info)


win = tk.Tk()
win.title('全國各地歷史天氣查詢系統')
win.geometry('500x500')

# 畫布  設定背景圖片
canvas = tk.Canvas(win, height=500, width=500)
im_root = get_image('test.jpg', width=500, height=500)
canvas.create_image(250, 250, image=im_root)
canvas.pack()

# 單行文字
L1 = tk.Label(win, bg='yellow', text="地區:", font=("SimHei", 12))
L2 = tk.Label(win, bg='yellow', text="時間:", font=("SimHei", 12))
L1.place(x=85, y=100)
L2.place(x=85, y=150)

# 單行文字框  可採集鍵盤輸入
b1 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b2 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b1.place(x=140, y=100)
b2.place(x=140, y=150)

# 設定查詢按鈕
a = tk.Button(win, bg='red', text="查詢", width=25, height=2, command=spider)
a.place(x=160, y=200)

# 設定多行文字框  寬 高  文字框中字型  選中文字時文字的顏色
t = tk.Text(win, width=30, height=8, font=("SimHei", 18), selectforeground='red')  # 顯示多行文字
t.place(x=70, y=280)

# 進入訊息迴圈
win.mainloop()

2. 執行效果

執行效果如下:

二、基本思路

匯入用到的庫

import requests
from lxml import etree
import re
import tkinter as tk
from PIL import Image, ImageTk
from xpinyin import Pinyin

1. 爬蟲部分

目標url:https://lishi.tianqi.com/

該網站提供了全國34個省、市所屬的2290個地區的歷史天氣預報查詢,資料來源於城市當天的天氣資訊,可以查詢到歷史天氣氣溫,歷史風向,歷史風力等歷史天氣狀況。

分析網頁可以發現,某個地區、某個月的所有天氣資料的url為:https://lishi.tianqi.com/ + 地區名字的拼音 + ‘/’ + 年月.html。

根據使用者輸入的地區和時間,進行字串的處理,構造出url,用於request請求有該月所有天氣資訊的頁面,獲取響應後Xpath定位提取使用者輸入的要查詢的日期的天氣資訊,查詢結果顯示在tkinter介面。

爬蟲程式碼如下:

def spider():
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
        "referer": "https://lishi.tianqi.com/chengdu/index.html"
    }
    p = Pinyin()
    place = ''.join(p.get_pinyin(b1.get()).split('-'))           # 獲取地區文字框的輸入  變為拼音
    # 處理使用者輸入的時間
    # 規定三種格式都可以 2018/10/1  2018年10月1日  2018-10-1
    date = b2.get()   # 獲取時間文字框的輸入
    if '/' in date:
        tm_list = date.split('/')
    elif '-' in date:
        tm_list = date.split('-')
    else:
        tm_list = re.findall(r'\d+', date)

    if int(tm_list[1]) < 10:       # 1-9月  前面加 0
        tm_list[1] = f'0{tm_list[1]}'
    # 分析網頁發現規律   構造url
    # 直接訪問有該月所有天氣資訊的頁面 提高查詢效率
    url = f"https://lishi.tianqi.com/{place}/{''.join(tm_list[:2])}.html"
    resp = requests.get(url, headers=headers)
    html = etree.HTML(resp.text)
    # xpath定位提取該日天氣資訊
    info = html.xpath(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')
    # 輸出資訊格式化一下
    info1 = ['日期:', '最高氣溫:', '最低氣溫:', '天氣:', '風向:']
    datas = [i + j for i, j in zip(info1, info)]
    info = '\n'.join(datas)
    t.insert('insert', '        查詢結果如下        \n\n')
    t.insert('insert', info)
    print(info)

2. tkinter介面

程式碼如下:

def get_image(file_nam, width, height):
    im = Image.open(file_nam).resize((width, height))
    return ImageTk.PhotoImage(im)


win = tk.Tk()
# 設定視窗title和大小
win.title('全國各地歷史天氣查詢系統')
win.geometry('500x500')

# 畫布  設定背景圖片
canvas = tk.Canvas(win, height=500, width=500)
im_root = get_image('test.jpg', width=500, height=500)
canvas.create_image(250, 250, image=im_root)
canvas.pack()

# 單行文字
L1 = tk.Label(win, bg='yellow', text="地區:", font=("SimHei", 12))
L2 = tk.Label(win, bg='yellow', text="時間:", font=("SimHei", 12))
L1.place(x=85, y=100)
L2.place(x=85, y=150)

# 單行文字框  可採集鍵盤輸入
b1 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b2 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b1.place(x=140, y=100)
b2.place(x=140, y=150)

# 設定查詢按鈕  點選 呼叫爬蟲函式實現查詢
a = tk.Button(win, bg='red', text="查詢", width=25, height=2, command=spider)
a.place(x=160, y=200)

# 設定多行文字框  寬 高  文字框中字型  選中文字時文字的顏色
t = tk.Text(win, width=30, height=8, font=("SimHei", 18), selectforeground='red')  # 顯示多行文字
t.place(x=70, y=280)

# 進入訊息迴圈
win.mainloop()

tkinter介面效果如下: