|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +北邮图书馆《埃隆·马斯克传》西土城校区在架可借状态监控脚本 |
| 4 | +每15分钟检查一次,如有西土城在架可借则通过Bark通知 |
| 5 | +
|
| 6 | +其实多match了一个,检测结果是4本,但是无所谓 |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import re |
| 11 | +import sys |
| 12 | +import time |
| 13 | +import logging |
| 14 | +import urllib.request |
| 15 | +import urllib.error |
| 16 | +import urllib.parse |
| 17 | +from datetime import datetime |
| 18 | + |
| 19 | +# ============ 配置 ============ |
| 20 | +BOOK_URL = "http://opac.bupt.edu.cn:8080//bookInfo_01h0483291.html" |
| 21 | +BARK_URL = "http://localhost:xxxx/xxxxxxxx" |
| 22 | +CHECK_INTERVAL = 15 * 60 # 15分钟(秒) |
| 23 | +TIMEOUT = 15 # HTTP请求超时(秒) |
| 24 | + |
| 25 | +logging.basicConfig( |
| 26 | + level=logging.INFO, |
| 27 | + format="%(asctime)s [%(levelname)s] %(message)s", |
| 28 | + datefmt="%Y-%m-%d %H:%M:%S", |
| 29 | +) |
| 30 | +log = logging.getLogger(__name__) |
| 31 | + |
| 32 | + |
| 33 | +def fetch_page(url): |
| 34 | + """获取页面HTML内容""" |
| 35 | + req = urllib.request.Request( |
| 36 | + url, |
| 37 | + headers={ |
| 38 | + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " |
| 39 | + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", |
| 40 | + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", |
| 41 | + }, |
| 42 | + ) |
| 43 | + with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: |
| 44 | + charset = resp.headers.get_content_charset() or "utf-8" |
| 45 | + return resp.read().decode(charset) |
| 46 | + |
| 47 | + |
| 48 | +def parse_collection(html): |
| 49 | + """ |
| 50 | + 用正则解析馆藏表格。 |
| 51 | + 匹配每个<tr>块中同时包含条码号和馆藏部门/状态的行。 |
| 52 | + """ |
| 53 | + results = [] |
| 54 | + barcode_pattern = re.compile(r"2111\d{10}") |
| 55 | + dept_pattern = re.compile(r"((?:西土城|沙河)[::][^<\n]+)") |
| 56 | + status_keywords = ["在架可借", "本馆借出", "阅览", "预约", "装订中", "编目中"] |
| 57 | + |
| 58 | + tr_blocks = re.findall(r"<tr[^>]*>(.*?)</tr>", html, re.DOTALL | re.IGNORECASE) |
| 59 | + for block in tr_blocks: |
| 60 | + found_barcode = barcode_pattern.search(block) |
| 61 | + if not found_barcode: |
| 62 | + continue |
| 63 | + barcode = found_barcode.group() |
| 64 | + |
| 65 | + # 提取馆藏部门 |
| 66 | + dept_match = dept_pattern.search(block) |
| 67 | + dept = dept_match.group(1).strip() if dept_match else "" |
| 68 | + dept = re.sub(r"<[^>]+>", "", dept).strip() |
| 69 | + |
| 70 | + # 提取状态 |
| 71 | + status = "" |
| 72 | + for kw in status_keywords: |
| 73 | + if kw in block: |
| 74 | + status = kw |
| 75 | + break |
| 76 | + |
| 77 | + if dept or status: |
| 78 | + results.append({ |
| 79 | + "department": dept, |
| 80 | + "barcode": barcode, |
| 81 | + "status": status, |
| 82 | + }) |
| 83 | + |
| 84 | + return results |
| 85 | + |
| 86 | + |
| 87 | +def send_bark_notification(title, body): |
| 88 | + """通过Bark发送通知""" |
| 89 | + encoded_title = urllib.parse.quote(title, safe="") |
| 90 | + encoded_body = urllib.parse.quote(body, safe="") |
| 91 | + url = "{}/{}/{}".format(BARK_URL, encoded_title, encoded_body) |
| 92 | + try: |
| 93 | + req = urllib.request.Request(url) |
| 94 | + with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: |
| 95 | + log.info("Bark通知发送成功,响应码: %d", resp.status) |
| 96 | + return True |
| 97 | + except Exception as e: |
| 98 | + log.error("Bark通知发送失败: %s", e) |
| 99 | + return False |
| 100 | + |
| 101 | + |
| 102 | +def check_once(): |
| 103 | + """执行一次检查,返回西土城在架可借的记录列表""" |
| 104 | + log.info("开始检查馆藏状态...") |
| 105 | + try: |
| 106 | + html = fetch_page(BOOK_URL) |
| 107 | + except Exception as e: |
| 108 | + log.error("获取页面失败: %s", e) |
| 109 | + return [] |
| 110 | + |
| 111 | + all_items = parse_collection(html) |
| 112 | + log.info("共解析到 %d 条馆藏记录", len(all_items)) |
| 113 | + for item in all_items: |
| 114 | + log.info(" %s | %s | %s", item["department"], item["barcode"], item["status"]) |
| 115 | + |
| 116 | + # 筛选西土城 + 在架可借 |
| 117 | + available = [ |
| 118 | + item for item in all_items |
| 119 | + if "西土城" in item.get("department", "") and "在架可借" in item.get("status", "") |
| 120 | + ] |
| 121 | + # available = [ |
| 122 | + # {"department": "西土城", "status": "在架可借", "barcode": "mock123"} |
| 123 | + # ] |
| 124 | + return available |
| 125 | + |
| 126 | + |
| 127 | +def main(): |
| 128 | + """主循环""" |
| 129 | + run_once = "--once" in sys.argv |
| 130 | + |
| 131 | + while True: |
| 132 | + now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 133 | + available = check_once() |
| 134 | + |
| 135 | + if available: |
| 136 | + log.info("发现 %d 本西土城在架可借!", len(available)) |
| 137 | + details = "\n".join( |
| 138 | + "{} 条码:{}".format(r["department"], r["barcode"]) |
| 139 | + for r in available |
| 140 | + ) |
| 141 | + title = "北邮图书馆-马斯克传有书可借" |
| 142 | + body = "西土城校区发现{}本在架可借\n{}\n检查时间:{}".format( |
| 143 | + len(available), details, now |
| 144 | + ) |
| 145 | + send_bark_notification(title, body) |
| 146 | + break |
| 147 | + else: |
| 148 | + log.info("暂无西土城在架可借,%d分钟后再查...", CHECK_INTERVAL // 60) |
| 149 | + |
| 150 | + if run_once: |
| 151 | + break |
| 152 | + |
| 153 | + time.sleep(CHECK_INTERVAL) |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + main() |
0 commit comments