今天由于特别关心佩洛西动向,又不想隔一会去刷一下百度,所以写了个脚本,自动去抓消息并调用电脑的桌面通知。
let curTitle = document.querySelector(".title_3R7GH").text;
// 先通过Notification.requestPermission获取通知权限
Notification.requestPermission().then(function (result) {
if (result === "denied") {
alert("拒绝显示系统通知");
return;
}
if (result === "default") {
console.log("默认");
return;
}
console.log("允许显示系统通知");
setInterval(() => {
const title = document.querySelector(".title_3R7GH").text;
if (title !== curTitle) {
var notify = new Notification("佩洛西最新消息", {
body: title,
});
curTitle = title;
} else {
// 没有结果就点一下搜索按钮,重新拉一下数据
document.querySelector(".bg .s_btn").click();
}
}, 1000*60*3);
});
上面的脚本写完,F12唤起控制台,然后放进去运行就行了。 那么,有兄弟就要问了,太麻烦了,我还得保持网页不关闭,有没有不开网页也可以的。呐,nodejs版本的来了。
需要安装的包
npm install xpath xmldom htmlparser2 node-notifier -D --save
正文
const xpath = require("xpath");
const DOMParser = require("xmldom").DOMParser;
const htmlparser2 = require("htmlparser2");
const notifier = require("node-notifier");
let title = "";
const domParser = new DOMParser();
function loadPage(url) {
var http = require("https");
var pm = new Promise(function (resolve, reject) {
http
.get(url, function (res) {
var html = "";
res.on("data", function (d) {
html += d.toString();
});
res.on("end", function () {
resolve(html, "end");
});
})
.on("error", function (e) {
reject(e);
});
});
return pm;
}
setInterval(() => {
loadPage(
"https://events.baidu.com/search/vein?platform=pc&record_id=1676"
).then(function (html) {
// 不用用 htmlparser2 转换直接解析有时候会报错
const outerHTML = htmlparser2.DomUtils.getOuterHTML(
htmlparser2.parseDOM(html)
);
let doc = domParser.parseFromString(outerHTML);
let nodes = xpath.select("//a[@class='content-link c-line-clamp1']", doc);
if (title !== nodes[0].firstChild.data) {
notifier.notify(nodes[0].firstChild.data);
title = nodes[0].firstChild.data;
}
});
}, 1000 * 60 * 3);
当然,有些兄弟有服务器的,可以用公众号推送消息,或者用wechaty推送消息。免费的可以用wxmnode,注册一个账号就可以使用。
最后,希望祖国繁荣富强!