Python番外篇:爬取比特币实时价格 并通过GUI窗体展示

824 阅读1分钟

本人已参与【新人创作礼】活动,一起开启掘金创作之路。 本文首发于CSDN

hello,大家好,我是wangzirui32,今天来教大家如何爬取比特币实时价格,并通过GUI窗体展示,开始学习吧!

1. 网页分析

在本章使用的数据来自www.coindesk.com/price/bitco…,开始分析:
Html解析
待会我们会用bs4来获取这个div标签的内容,并把“$”符号去掉。

2. 爬取代码

from requests import get
from bs4 import BeautifulSoup

r = get("https://www.coindesk.com/price/bitcoin")
soup = BeautifulSoup(r.text, "html.parser")
price = soup.find("div", {'class': "price-large"}).replace("$")   # 读取价格
print(price)

运行代码,输出:

35,207.14

这样就完成了爬取部分。

3. GUI窗体代码

from requests import get
import tkinter as tk
import datetime
from bs4 import BeautifulSoup

def get_prince():
    """获取比特币价格并返回"""
    r = get("https://www.coindesk.com/price/bitcoin")
    soup = BeautifulSoup(r.text, "html.parser")
    price = soup.find("div", {'class': "price-large"}).text.replace("$", "")   # 读取价格

    return price

# 窗体类
class Window(tk.Tk):
    def __init__(self):
        super().__init__()

        # 基本窗体设置
        self.title("比特币实时价格")
        self.geometry("500x150")
        self.config(bg="black")

        # 字体类别 大小设置
        # 注意:这里使用的是Windows 10系统的自带字体
        self.title_label_font = ("Bahnschrift Light", 45)
        self.price_label_font = ("Bahnschrift Light", 30)
        self.time_label_font = ("Bahnschrift Light", 15)

        self.show_data()                   # 初始化屏幕上的数据
        self.after(10000, self.show_data)  # 每隔10秒刷新数据

    def show_data(self):
        # 显示标题
        self.title_label = tk.Label(self,
                                    text="BTC Price",
                                    font=self.title_label_font,
                                    bg="black",
                                    fg='cyan')
        self.title_label.pack()

        # 获取价格并显示到屏幕上
        price = "$ " + get_prince() + " USD"
        self.price_label = tk.Label(self,
                               text=price,
                               font=self.price_label_font,
                               bg="black",
                               fg="cyan")
        self.price_label.pack()
        # 获取当前时间并显示到屏幕上
        now_time = datetime.datetime.now()
        now_time = now_time.strftime("%Y-%m-%d %H:%M")  # 格式化时间

        self.time_label = tk.Label(self,
                                    text=now_time,
                                    font=self.time_label_font,
                                    bg="black",
                                    fg="cyan")
        self.time_label.pack()


app = Window()
app.mainloop()

运行代码,效果如下:
效果


好了,今天的课程就到这里,我是wangzirui32,我们下次再见!