教你怎么用Python监控愉客行车程

一、愉客行车程监控并通知

大概思路:用户填写指定信息在config.json文件中,通过定时访问网页,获取指定信息,从而达到对指定车程的监控

1.分析网页

按下F12,打开开发者工具,再刷新一下网页

找到我们需要的信息

然后再分析一下它的请求方式

很直观的就看到了几条主要的信息

第一条和第三条是null不重要
第二条是起始站
第四条是终点站
第五条是个数字,经过反复尝试,发现是固定参数
第六条乍一看应该是时间戳,经过验证,的确是车票指定日期零点的时间戳

2.请求头伪装、带参访问指定网页,获取信息:

def get_html(startStation, endStation, timeStamp):
    # 模拟请求
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-HK;q=0.6',
        'Connection': 'keep-alive',
        'Content-Length': '124',
        'Content-Type': 'application/json; charset=UTF-8',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
        'sec-ch-ua-mobile': '?0',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'cross-site',
        'Host': 'busserver.cqyukexing.com',
        'Origin': 'https://www.96096kp.com',
        'Referer': 'https://www.96096kp.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36',
    }
    data = {
        'departureName': startStation,
        'destinationId': 'null',
        'destinationName': endStation,
        'opSource': '7',
        # 指定日期时间戳
        'queryDate': timeStamp,
    }
    data = json.dumps(data)
    url = 'https://busserver.cqyukexing.com/busticket/schedule_list_310?channel=7'
    response = requests.post(url, headers=headers, data=data, timeout=5)
    if response.status_code == 200:
        html = response.text
        # print(html)
        return html

3.将返回的数据解析

因为请求获得的数据是json格式的,所以用jsonpath做数据解析

def parse_html(html):
    # 解析获取的数据
    items = []
    html = json.loads(html)
    for i in range(len(jsonpath.jsonpath(html, '$..scheduleInfo'))):
        item = {}
        timeStamp = jsonpath.jsonpath(html, '$..scheduleInfo..departureTime')[i]
        item["发车日期"] = time.strftime("%Y-%m-%d", time.localtime(timeStamp))
        # 检测是否过期
        out_data(item["发车日期"])
        item["发车时间"] = jsonpath.jsonpath(html, '$..scheduleInfo..departureTimeDesc')[i]
        item["起始站"] = jsonpath.jsonpath(html, '$..departureStation..name')[i]
        # item["地址"] = jsonpath.jsonpath(html, '$..departureStation..addr')[i]
        item["终点站"] = jsonpath.jsonpath(html, '$..destinationStation..name')[i]
        item["余票"] = jsonpath.jsonpath(html, '$..scheduleInfo..remainSeatCnt')[i]
        item["票价"] = jsonpath.jsonpath(html, '$..scheduleInfo..fullTicketPrice')[i]
        item["车型"] = jsonpath.jsonpath(html, '$..scheduleInfo..busType')[i]
        item["车牌号"] = jsonpath.jsonpath(html, '$..scheduleInfo..scheduleCode')[i]
        item["路线"] = jsonpath.jsonpath(html, '$..scheduleInfo..lineName')[i][3:]
        item["状态"] = '\033[32m' if item["余票"] > 0 else '\033[31m'
        # item["途径"] = jsonpath.jsonpath(html, '$..scheduleInfo..stopStation')[i]
        items.append(item)
    return items

4.筛选出有票的车次

这里是将已经获取过的车次保存到文件中,一旦检测到新的车次,就准备通知,如果检测到没有新车次,不做通知

def watch_ticks(bus_list):
    # 检查目前还有票的车次
    format_info(bus_list)
    has_ticks = []
    filename = 'tick_log of ' + bus_list[0]["起始站"] + '-' + bus_list[0]["终点站"] + '.txt'
    # 如果log文件不存在,则新建一个空的文件
    if not os.path.exists('./logs/' + filename):
        f = open('./logs/' + filename, 'w')
        f.close()
    with open('./logs/' + filename, 'r+', encoding='utf-8') as file:
        alreald_send = file.read()
    for bus in bus_list:
        if bus["余票"] != 0 and bus["发车时间"] not in alreald_send or not len(alreald_send):
            has_ticks.append(bus)
            with open('./logs/tick_log of ' + bus["起始站"] + '-' + bus["终点站"] + '.txt', 'a+', encoding='utf-8') as file:
                file.write(bus["发车时间"] + '\n')
    # print(has_ticks)
    return has_ticks

5.格式化终端输出信息

输出车程信息,这里改了终端车次显示的颜色,有票的是绿色、没票的是红色,很快就能识别出自己想要的

def format_info(bus_list):
    print(bus_list[0]["发车日期"] + '\t' + bus_list[0]["起始站"] + '-' + bus_list[0]["终点站"])
    print('-' * 120)
    # print("\t发车时间"
    #       "\t\t\t起始站"
    #       "\t\t\t终点站"
    #       "\t\t余票"
    #       "\t\t票价"
    #       "\t\t路线"
    #       "\t\t车型"
    #       "\t\t车牌号")
    for bus in bus_list:
        print(bus["状态"] + "\t" + bus["发车时间"],
              "\t\t" + bus["起始站"],
              "\t\t" + bus["终点站"],
              "\t\t" + str(bus["余票"]),
              "\t\t\t" + str(bus["票价"]),
              "\t\t" + bus["路线"],
              "\t\t" + bus["车型"],
              "\t\t" + bus["车牌号"] + '\033[0m')
    print('-' * 120)

6.设定邮件通知

这里代码是以前的,我直接拿来改了一下

def send_email(sendUser, mail_user, mail_pass, receivers, start, end, tick_date, message):
    """发送邮件"""
    # 第三方 SMTP 服务
    mail_host = 'smtp.qq.com'  # 设置服务器
    sender = mail_user

    # 创建一个带附件的案例
    mail = MIMEMultipart()

    mail['From'] = Header(sendUser, 'utf-8')
    mail['To'] = ";".join(receivers)
    subject = '愉客行有新的票务情况:' + tick_date + '-' + start + '-' + end  # 邮件标题
    mail['Subject'] = Header(subject, 'utf-8')

    # 邮件正文内容
    mail.attach(MIMEText(message, 'plain', 'utf-8'))

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25为端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, mail.as_string())
        print(receivers + "\t发送成功")  # 邮件发送成功
    except Exception as e:
        pass
    finally:
        smtpObj.quit()

7.设定主函数

这里把用户输入的信息转换一下,将日期转为时间戳,并且可支持多车程的监控,配置文件应一一对应。
将获取到的车程信息保存
如果有变化,立刻发送邮件通知
设定了定时执行,这里是每隔30分钟执行一次

def main():
    global timer_times
    timer_times = timer_times + 1
    for i in range(len(startStation)):
        html = get_html(startStation[i], endStation[i], timeStamp[i])
        bus_list = parse_html(html)
        # pprint.pprint(bus_list)
        has_ticks = watch_ticks(bus_list)
        json.dump(bus_list,
                  open('./data/bus_list of ' + startStation[i] + '-' + endStation[i] + '.json', 'a+', encoding='utf-8'),
                  ensure_ascii=False)
        if len(has_ticks):
            json.dump(has_ticks, open('./data/has_ticks of ' + startStation[i] + '-' + endStation[i] + '.json', 'w+',
                                      encoding='utf-8'), ensure_ascii=False)
            message = '\n'.join([str(tick).replace(',', '\n') for tick in has_ticks])
            send_email(sendUser[i], mail_user[i], mail_pass[i], receivers[i], startStation[i], endStation[i],
                       ticksDate[i], message)
    # 定时延迟
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    log_message = ("\n定时任务已触发至:第%s轮\n当前时间:%s\n" % (timer_times, now))
    with open("./logs/log.txt", 'a+', encoding="utf-8") as file:
        file.write(log_message)
    print(log_message)
    time.sleep(1800)
    timer = threading.Timer(1800, main())
    timer.start()

8.程序入口

获取config.json文件的信息,执行main函数,开始定时任务

if __name__ == '__main__':
    with open('config.json', 'r', encoding='utf-8') as file:
        config = json.load(file)
    startStation = config["起始站"]
    endStation = config["终点站"]
    ticksDate = config["车票日期"]
    timeArray = [time.strptime(tick_date + ' 00:00:00', "%Y-%m-%d %H:%M:%S") for tick_date in config["车票日期"]]
    timeStamp = [int(time.mktime(times)) for times in timeArray]
    sendUser = config["发送人"]
    mail_user = config["用户名"]
    mail_pass = config["第三方客户端授权码"]
    receivers = config["接收方"]
    # 定时延迟
    timer_times = 0
    timer = threading.Timer(1800, main())
    timer.start()

本来是想挂到服务器上,就做了一个检测日期的函数,如果车程日期在当前日期之前,就直接退出程序,最后还是在本地上运行的,就没用的上

def out_data(date):
    # 检查车票跟踪是否过时
    # 是否过期一天
    tomorrow = datetime.date.today() - datetime.timedelta(days=1)
    if date == tomorrow:
        print("车票跟踪已过时!")
        os.exit(0)

9.结果图

二、目录结构

三、完整代码

import datetime
import os
import smtplib
import threading
import time
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import requests
import json
import jsonpath

def get_html(startStation, endStation, timeStamp):
    # 模拟请求
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-HK;q=0.6',
        'Connection': 'keep-alive',
        'Content-Length': '124',
        'Content-Type': 'application/json; charset=UTF-8',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
        'sec-ch-ua-mobile': '?0',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'cross-site',
        'Host': 'busserver.cqyukexing.com',
        'Origin': 'https://www.96096kp.com',
        'Referer': 'https://www.96096kp.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36',
    }
    data = {
        'departureName': startStation,
        'destinationId': 'null',
        'destinationName': endStation,
        'opSource': '7',
        # 指定日期时间戳
        'queryDate': timeStamp,
    }
    data = json.dumps(data)
    url = 'https://busserver.cqyukexing.com/busticket/schedule_list_310?channel=7'
    response = requests.post(url, headers=headers, data=data, timeout=5)
    if response.status_code == 200:
        html = response.text
        # print(html)
        return html

def parse_html(html):
    # 解析获取的数据
    items = []
    html = json.loads(html)
    for i in range(len(jsonpath.jsonpath(html, '$..scheduleInfo'))):
        item = {}
        timeStamp = jsonpath.jsonpath(html, '$..scheduleInfo..departureTime')[i]
        item["发车日期"] = time.strftime("%Y-%m-%d", time.localtime(timeStamp))
        # 检测是否过期
        out_data(item["发车日期"])
        item["发车时间"] = jsonpath.jsonpath(html, '$..scheduleInfo..departureTimeDesc')[i]
        item["起始站"] = jsonpath.jsonpath(html, '$..departureStation..name')[i]
        # item["地址"] = jsonpath.jsonpath(html, '$..departureStation..addr')[i]
        item["终点站"] = jsonpath.jsonpath(html, '$..destinationStation..name')[i]
        item["余票"] = jsonpath.jsonpath(html, '$..scheduleInfo..remainSeatCnt')[i]
        item["票价"] = jsonpath.jsonpath(html, '$..scheduleInfo..fullTicketPrice')[i]
        item["车型"] = jsonpath.jsonpath(html, '$..scheduleInfo..busType')[i]
        item["车牌号"] = jsonpath.jsonpath(html, '$..scheduleInfo..scheduleCode')[i]
        item["路线"] = jsonpath.jsonpath(html, '$..scheduleInfo..lineName')[i][3:]
        item["状态"] = '\033[32m' if item["余票"] > 0 else '\033[31m'
        # item["途径"] = jsonpath.jsonpath(html, '$..scheduleInfo..stopStation')[i]
        items.append(item)
    return items

def watch_ticks(bus_list):
    # 检查目前还有票的车次
    format_info(bus_list)
    has_ticks = []
    filename = 'tick_log of ' + bus_list[0]["起始站"] + '-' + bus_list[0]["终点站"] + '.txt'
    # 如果log文件不存在,则新建一个空的文件
    if not os.path.exists('./logs/' + filename):
        f = open('./logs/' + filename, 'w')
        f.close()
    with open('./logs/' + filename, 'r+', encoding='utf-8') as file:
        alreald_send = file.read()
    for bus in bus_list:
        if bus["余票"] != 0 and bus["发车时间"] not in alreald_send or not len(alreald_send):
            has_ticks.append(bus)
            with open('./logs/tick_log of ' + bus["起始站"] + '-' + bus["终点站"] + '.txt', 'a+', encoding='utf-8') as file:
                file.write(bus["发车时间"] + '\n')
    # print(has_ticks)
    return has_ticks

def out_data(date):
    # 检查车票跟踪是否过时
    # 是否过期一天
    tomorrow = datetime.date.today() - datetime.timedelta(days=1)
    if date == tomorrow:
        print("车票跟踪已过时!")
        os.exit(0)

def format_info(bus_list):
    print(bus_list[0]["发车日期"] + '\t' + bus_list[0]["起始站"] + '-' + bus_list[0]["终点站"])
    print('-' * 120)
    # print("\t发车时间"
    #       "\t\t\t起始站"
    #       "\t\t\t终点站"
    #       "\t\t余票"
    #       "\t\t票价"
    #       "\t\t路线"
    #       "\t\t车型"
    #       "\t\t车牌号")
    for bus in bus_list:
        print(bus["状态"] + "\t" + bus["发车时间"],
              "\t\t" + bus["起始站"],
              "\t\t" + bus["终点站"],
              "\t\t" + str(bus["余票"]),
              "\t\t\t" + str(bus["票价"]),
              "\t\t" + bus["路线"],
              "\t\t" + bus["车型"],
              "\t\t" + bus["车牌号"] + '\033[0m')
    print('-' * 120)

def send_email(sendUser, mail_user, mail_pass, receivers, start, end, tick_date, message):
    """发送邮件"""
    # 第三方 SMTP 服务
    mail_host = 'smtp.qq.com'  # 设置服务器
    sender = mail_user

    # 创建一个带附件的案例
    mail = MIMEMultipart()

    mail['From'] = Header(sendUser, 'utf-8')
    mail['To'] = ";".join(receivers)
    subject = '愉客行有新的票务情况:' + tick_date + '-' + start + '-' + end  # 邮件标题
    mail['Subject'] = Header(subject, 'utf-8')

    # 邮件正文内容
    mail.attach(MIMEText(message, 'plain', 'utf-8'))

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25为端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, mail.as_string())
        print(receivers + "\t发送成功")  # 邮件发送成功
    except Exception as e:
        pass
    finally:
        smtpObj.quit()

def main():
    global timer_times
    timer_times = timer_times + 1
    for i in range(len(startStation)):
        html = get_html(startStation[i], endStation[i], timeStamp[i])
        bus_list = parse_html(html)
        # pprint.pprint(bus_list)
        has_ticks = watch_ticks(bus_list)
        json.dump(bus_list,
                  open('./data/bus_list of ' + startStation[i] + '-' + endStation[i] + '.json', 'a+', encoding='utf-8'),
                  ensure_ascii=False)
        if len(has_ticks):
            json.dump(has_ticks, open('./data/has_ticks of ' + startStation[i] + '-' + endStation[i] + '.json', 'w+',
                                      encoding='utf-8'), ensure_ascii=False)
            message = '\n'.join([str(tick).replace(',', '\n') for tick in has_ticks])
            send_email(sendUser[i], mail_user[i], mail_pass[i], receivers[i], startStation[i], endStation[i],
                       ticksDate[i], message)
    # 定时延迟
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    log_message = ("\n定时任务已触发至:第%s轮\n当前时间:%s\n" % (timer_times, now))
    with open("./logs/log.txt", 'a+', encoding="utf-8") as file:
        file.write(log_message)
    print(log_message)
    time.sleep(1800)
    timer = threading.Timer(1800, main())
    timer.start()

if __name__ == '__main__':
    with open('config.json', 'r', encoding='utf-8') as file:
        config = json.load(file)
    startStation = config["起始站"]
    endStation = config["终点站"]
    ticksDate = config["车票日期"]
    timeArray = [time.strptime(tick_date + ' 00:00:00', "%Y-%m-%d %H:%M:%S") for tick_date in config["车票日期"]]
    timeStamp = [int(time.mktime(times)) for times in timeArray]
    sendUser = config["发送人"]
    mail_user = config["用户名"]
    mail_pass = config["第三方客户端授权码"]
    receivers = config["接收方"]
    # 定时延迟
    timer_times = 0
    timer = threading.Timer(1800, main())
    timer.start()

四、config.json文件

{
  "车票日期": [
    "2021-4-30",
    "2021-5-5"
  ],
  "起始站": [
    "万州",
    "彭水县"
  ],
  "终点站": [
    "涪陵",
    "万州"
  ],
  "发送人": [
    "愉客行",
    "愉客行"
  ],
  "用户名": [
    "1*******27@qq.com",
    "1*******27@qq.com"
  ],
  "第三方客户端授权码": [
    "oxms********iicj",
    "oxms********iicj"
  ],
  "接收方": [
    "265******8@qq.com",
    "265******8@qq.com"
  ]
}

到此这篇关于教你怎么用Python监控愉客行车程的文章就介绍到这了,更多相关Python监控愉客行车程内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python 自动监控最新邮件并读取的操作

    我就废话不多说了,大家还是直接看代码吧~ #zmail库:可以用几行代码帮我们收取一封邮件 import zmail #输入账号和密码 server=zmail.server('13163964546@qq.com','jie110341') #获取最新的一封邮件 mail=server.get_latest() #读取邮件 #zmail.show(mail) #读取邮件的部分内容 print(mail['subject']) ...... #读取附件 邮件 存放路径 如果有同名文件则覆盖 zm

  • 通过Python实现对SQL Server 数据文件大小的监控告警功能

    1.需求背景 系统程序突然报错,报错信息如下: The transaction log for database '@dbname' is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases 此时查看log文件,已达2T. 当时的紧急处理方案是,移除掉镜像,修改数据库恢复模式(由full修改为simple),收缩日志. 为了防止类似

  • 如何基于Python和Flask编写Prometheus监控

    介绍 Prometheus 的基本原理是通过 HTTP 周期性抓取被监控组件的状态. 任意组件只要提供对应的 HTTP 接口并且符合 Prometheus 定义的数据格式,就可以接入 Prometheus 监控. Prometheus Server 负责定时在目标上抓取 metrics(指标)数据并保存到本地存储.它采用了一种 Pull(拉)的方式获取数据,不仅降低客户端的复杂度,客户端只需要采集数据,无需了解服务端情况,也让服务端可以更加方便地水平扩展. 如果监控数据达到告警阈值,Promet

  • 用python监控服务器的cpu,磁盘空间,内存,超过邮件报警

    监控Linux服务器嘛,脚本逻辑基本上是用os.popen模块,然后把获取到的结果通过split切分成一个list,再拿目标list值和我阈值对比,超过就邮件报警: 邮件是通过Linux的mailx发出去的,可自行搜索安装该模块,关键字:"Linux使用mailx发邮件",脚本如下: 一.cpu ideal值,不小于20% #!/usr/bin/python # -*- coding: utf-8 -*-   import datetime import os     f = os.p

  • python自动统计zabbix系统监控覆盖率的示例代码

    脚本主要功能: 1)通过zabbix api接口采集所有监控主机ip地址: 2)通过cmdb系统(蓝鲸)接口采集所有生产主机IP地址.主机名.操作系统.电源状态: 3)以上2步返回数据对比,找出未监控主机ip地址,生成csv文件: 4)发送邮件. 脚本如下: #!/usr/bin/python #coding:utf-8 import requests import json import re import time import csv from collections import Cou

  • Python实现用手机监控远程控制电脑的方法

    一.前言 很多时候,我们都有远程控制电脑的需求.比如正在下载某样东西,需要让电脑在下载完后关机.或者你需要监控一个程序的运行状况等. 今天我们就来用Python实现一个远程监控并控制电脑的小程序. 二.实现原理 听起来远程控制电脑好像很高级的样子,但是实现起来其实非常简单.实现原理如下: 运行程序,让程序不停地读取邮件 用手机给电脑发送邮件 判断是否读取到指定主题的邮件,如果有,则获取邮件内容 根据邮件内容,执行预设的函数 与其说是学习如何远程控制电脑,还不如说是学习如何读取邮件.当然,上面的的

  • python实现的web监控系统

    完整项目地址: https://github.com/zsjtoby/DevOpsCloud 欢迎使用极云监控系统 极云监控系统实现了跳板机应有的功能.基于ssh协议来管理,客户端无需安装agent. 支持常见系统: CentOS, RedHat, Fedora, Amazon Linux Debian SUSE, Ubuntu FreeBSD 其他ssh协议硬件设备 首页 WebTerminal: Web批量执行命令 录像回放 跳转和批量命令 命令统计 安装 cd /opt git clone

  • python 监控服务器是否有人远程登录(详细思路+代码)

    起源 当同一个远程服务器有多个人使用的时候,想知道服务器是否有人在用,我们不能直接的去登录,因为这样可能会把对方挤下来,这并不友好,所以这里提供一个监控远程服务器是否有人连接的方式 思路 遇到这个问题,想着如何去解决 刚开始的时候,我是想通过一个主动的方式,去监控到服务器是否有人连接,就是说当我想要知道服务器是否有人连接,我通过一个运行一个脚本程序,然后返回给我一个结果,事实证明,我并没有通过这样的思路解决这个问题 后来想以一个被动的方式来监控,比如在服务器上装载一个脚本,每5分钟运行一次脚本,

  • python基于watchdog库全自动化监控目录文件

    楔子 有些时候我们需要对一个目录进行监控,检测其内部是否有文件的新增.删除.以及每个文件的内容是否发生变化,这个时候如果是你的话,你会选择怎么做呢? 显然也是一个比较麻烦的工作,倒不是说难,主要是比较繁杂.但万幸的是,已经有一个第三方包watchdog帮我们完美地实现了这一点,所以这就是Python啊,想做什么都有现成的. 那么下面就来看一下它的用法,当然要先安装.直接:pip install watchdog即可. 使用方法 在我的桌面上有一个空目录test,一会儿我们对这个目录做的操作都会体

  • python使用Windows的wmic命令监控文件运行状况,如有异常发送邮件报警

       使用Windows的wmic命令,获取可执行文件的运行状况.文件路径.PID,如果可执行文件挂掉,就重启并邮件告警. 因为监控的可执行文件的文件名一样,不好区分,所以我使用文件的绝对路径为标准来判断是否正常运行,代码及详细解释如下: # -*- coding: utf-8 -*- import os import win32api import smtplib from email.mime.text import MIMEText def get_pidWay(file_name): e

  • python使用pynput库操作、监控你的鼠标和键盘

    楔子 python是一门很神奇的语言,原因在于它有很多的库可以实现各种意想不到的功能.当然我们这次介绍的库所实现的功能却是已经很常见了,就是操作.监控你的鼠标和键盘.如果你写过游戏,那么即使不用下面即将介绍的库也可以实现对鼠标.键盘的操作以及监控. 当然我们下面介绍库:pynput,是专门针对鼠标和键盘的,至于pygame.pyglet等游戏框架虽然也提供了鼠标.键盘的监控事件,但它们毕竟是用来开发游戏的,还提供了创建窗口.图形绘制.物体的碰撞检测等等很多复杂的功能.如果只是单纯的操作鼠标和键盘

随机推荐