自从有了编程伴侣,备忘的需求变得更低了,明显不担心记不住语法需要记录的情景。然而还是保持习惯,就当写日记吧,记录一下自己时不时在瞎捣腾啥。
tm,好人谁记日记。
就是监控灰色各自前紧挨着出现了多少红色格子。一共查灰色格子前12个格子,如果红色格子大于了8个,就得上去服务器看一眼。脚本写完用个定时程序隔1小时查查,足够了。
说起来,为了这个自己的项目,写了好几个监控,但是程序本身的log都防不住,出现的问题是专门跑项目的go程序之类的,日志里面居然不报错,但是明明就是漏了。
以下python脚本底层是在折腾爬虫针对动态页面的svg加载后元素变化的抓取,以及smtp邮件发送。放个雏形,这个不能线上用,不然false alarm太多。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
import time
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
# ===== 配置区 =====
SMTP_SERVER = "smtp.sohu.com" # 邮箱服务商SMTP地址
PORT = 465 # 端口号(SSL用465,TLS用587)
SENDER_EMAIL = "wawa@sohu.com" # 发件邮箱
SENDER_PASSWORD = "123" # 邮箱授权码(非登录密码)
RECIPIENT_EMAIL = "567@yahoo.com" # 收件邮箱
# ==================
def send_email(subject, content, is_html=False, attachments=None, images=None):
"""发送邮件核心函数"""
try:
# 1. 创建邮件容器
msg = MIMEMultipart()
msg["From"] = SENDER_EMAIL
msg["To"] = RECIPIENT_EMAIL
msg["Subject"] = subject
# 2. 添加邮件正文
content_type = "html" if is_html else "plain"
msg.attach(MIMEText(content, content_type, "utf-8"))
# 3. 添加附件(可选)
if attachments:
for file_path in attachments:
with open(file_path, "rb") as file:
part = MIMEApplication(file.read())
part.add_header("Content-Disposition", f"attachment; filename={file_path.split('/')[-1]}")
msg.attach(part)
# 4. 添加图片(可选)
if images:
for img_path, cid in images.items(): # cid用于HTML中引用
with open(img_path, "rb") as img_file:
img = MIMEImage(img_file.read())
img.add_header("Content-ID", f"<{cid}>")
msg.attach(img)
# 5. 连接SMTP服务器并发送
with smtplib.SMTP_SSL(SMTP_SERVER, PORT) as server: # SSL连接
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, msg.as_string())
print("✅ 邮件发送成功")
except Exception as e:
print(f"❌ 邮件发送失败: {str(e)}")
def fetch_dynamic_rect_ids_with_gecko():
# 配置Firefox无头模式
firefox_options = Options()
firefox_options.add_argument("--headless") # 无界面运行
firefox_options.set_preference("dom.webnotifications.enabled", False) # 禁用通知弹窗
# 设置geckodriver路径(需提前下载并配置)
# 下载地址:https://github.com/mozilla/geckodriver/releases
# gecko_path = os.path.join(os.getcwd(), "geckodriver") # Linux/macOS
gecko_path = "/usr/local/bin/geckodriver"
# gecko_path = r"C:\path\to\geckodriver.exe" # Windows路径示例
try:
# 初始化geckodriver服务
service = Service(executable_path=gecko_path)
driver = webdriver.Firefox(service=service, options=firefox_options)
driver.get("https://niyaojiankongde.wangzhan")
time.sleep(12)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 滚动到底部,用来欺骗服务器,是人在动
# 或模拟点击:driver.find_element(By.CSS_SELECTOR, "#trigger_button").click()
# 显式等待SVG内容渲染(关键步骤)
wait = WebDriverWait(driver,18)
rects = wait.until(EC.presence_of_all_elements_located(
(By.XPATH,"//*[local-name()='svg']//*[local-name()='rect']")
))
#WebDriverWait(driver, 15).until(
# EC.presence_of_all_elements_located((By.TAG_NAME, "rect")) # 此处疑似无效
# #EC.visibility_of_element_located((By.TAG_NAME,"rect")) # 此处疑似无效
# #EC.element_to_be_clickable((By.TAG_NAME,"rect"))
#)
#rects = driver.find_elements(By.TAG_NAME, "rect")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 滚动到底部,用来欺骗服务器,是人在动
time.sleep(1)
signal_mail = False
first_grey_id = "null"
match_red_ids = []
pattern_grey = re.compile(r'fill:\s*rgb\(\s*100\s*,\s*\d+\s*,\s*\d+\s*\)') # 匹配r=100的RGB样式,这是灰色
pattern_red = re.compile(r'fill:\s*rgb\(\s*176\s*,\s*\d+\s*,\s*\d+\s*\)') # 匹配r=176的RGB样式,这是红色特征
for rect in rects:
style = rect.get_attribute("style")
rect_id = rect.get_attribute("id")
if style and pattern_grey.search(style) and rect_id and first_grey_id == "null":
first_grey_id = rect_id
if style and pattern_red.search(style) and rect_id:
match_red_ids.append(rect_id)
# 进入第一个灰色方格,和它之前12个格子的颜色判断。
if first_grey_id != "null":
red_id_count_just_before_grey = 0
grey_id_num = first_grey_id.split("_")
grey_id_father = int(grey_id_num[1])
grey_id_son = int(grey_id_num[2])
for i in range [1:12]:
possible_red_id = "null"
k = grey_id_son - i
if k >= 0:
possible_red_id = "id_" + str(grey_id_father) + "_" + str(k)
elif k < 0 and grey_id_father > 0:
possible_red_id = "id_" + str(grey_id_father - 1) + "_" + str(k+34) #目前那个svg的小格子群图像,一共有33排。
else:
continue
if possbile_red_id != "null" and possible_red_id in match_red_ids:
red_id_count_just_before_grey = red_id_count_just_before_grey + 1
if red_id_count_just_before_grey > 7:
signal_mail = True
else:
pass
return signal_mail
except Exception as e:
send_email(
subject="破访问失败了",
content="你这程序写的不行",
)
return []
finally:
if 'driver' in locals():
driver.quit() # 确保资源释放
if __name__ == "__main__":
#print("🔥 启动Geckodriver动态解析...")
#start_time = time.time()
signal_sending = fetch_dynamic_rect_ids_with_gecko()
if signal_sending:
# 写个邮件发送程序,纯文本即可。
send_email(
subject="xx出现了8个红点",
content="xx出现了8个红点",
)
#print(f"\n✅ 发现 {len(result_ids)} 个匹配元素:")
#for idx, rect_id in enumerate(result_ids[:10], 1):
# print(f"{idx}. {rect_id}")
#if len(result_ids) > 10:
# print(f"(仅显示前10条,共{len(result_ids)}条)")
#print(f"\n⏱️ 总耗时: {time.time()-start_time:.2f}秒")