utils/parse/yandex-aon-fetch.user.js

67 lines
3.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// ==UserScript==
// @name Yandex AON collector (fetch)
// @namespace herzic
// @version 2.0
// @match https://ya.ru/*
// @grant GM_getValue
// @grant GM_setValue
// @run-at document-idle
// ==/UserScript==
// Как parse_link: страница не перезагружается, выдача берётся через fetch и разбирается DOMParser.
(function () {
'use strict';
const DELAY_MIN = 700, DELAY_MAX = 1500;
const S = {
get q() { return GM_getValue('q2', []); }, set q(v) { GM_setValue('q2', v); },
get res() { return GM_getValue('res2', {}); }, set res(v) { GM_setValue('res2', v); },
};
let running = false;
const box = document.createElement('div');
box.style.cssText = 'position:fixed;right:10px;bottom:10px;z-index:999999;background:#222;color:#fff;padding:10px;border-radius:8px;font:12px sans-serif;width:270px';
box.innerHTML = `<b>AON (fetch)</b><div id="st" style="margin:6px 0"></div>
<textarea id="in" placeholder="Номера, по одному в строке" style="width:100%;height:60px"></textarea>
<div style="display:flex;gap:4px;flex-wrap:wrap;margin-top:6px">
<button id="ld">Загрузить</button><button id="go">Старт</button><button id="sp">Стоп</button>
<button id="csv">CSV</button><button id="clr">Сброс</button></div>`;
document.body.appendChild(box);
const $ = id => box.querySelector('#' + id);
const st = m => $('st').textContent = `Готово: ${Object.keys(S.res).length}, осталось: ${S.q.length}. ${running ? 'Работает' : 'Стоп'}${m ? ' — ' + m : ''}`;
const sleep = ms => new Promise(r => setTimeout(r, ms));
$('ld').onclick = () => {
const res = S.res;
S.q = [...new Set($('in').value.split(/\s+/).map(s => s.replace(/\D/g, '')).filter(Boolean))].filter(n => !(n in res));
$('in').value = ''; st('загружено');
};
$('sp').onclick = () => { running = false; st(); };
$('clr').onclick = () => { if (confirm('Удалить очередь и результаты?')) { S.q = []; S.res = {}; st(); } };
$('csv').onclick = () => {
const rows = [['Номер', 'Яндекс']].concat(Object.entries(S.res));
const csv = '\uFEFF' + rows.map(r => r.map(c => '"' + String(c).replace(/"/g, '""') + '"').join(';')).join('\r\n');
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' })); a.download = 'yandex-aon.csv'; a.click();
};
$('go').onclick = async () => {
if (running) return; running = true;
while (running && S.q.length) {
const num = S.q[0];
let html;
try {
const r = await fetch('/search/?text=' + num, { credentials: 'include' });
if (/captcha/i.test(r.url)) { running = false; st('капча: открой ya.ru/search/?text=' + num + ' в этой вкладке, реши, вернись на ya.ru и жми Старт'); return; }
html = await r.text();
} catch (e) { st('ошибка сети, повтор'); await sleep(10000); continue; }
const doc = new DOMParser().parseFromString(html, 'text/html');
if (doc.querySelector('.CheckboxCaptcha, .AdvancedCaptcha, form[action*="captcha"]')) { running = false; st('капча, реши её на обычной вкладке и жми Старт'); return; }
const h = doc.querySelector('h3.AonProvider-Title');
const res = S.res; res[num] = h ? h.textContent.trim() : ''; S.res = res;
S.q = S.q.slice(1);
st(num + ': ' + (res[num] || 'нет блока'));
await sleep(DELAY_MIN + Math.random() * (DELAY_MAX - DELAY_MIN));
}
running = false; st(S.q.length ? '' : 'всё, жми CSV');
};
st();
})();