Spaces:
Running
Running
Download index.html from cliqtomedia/apify-web-scraper: direct link, hf CLI and curl.
- Browser
- Download file 29 kB
-
https://huggingface.co/spaces/cliqtomedia/apify-web-scraper/resolve/main/index.html
- Command line
-
hf download hf://spaces/cliqtomedia/apify-web-scraper/index.html
-
curl -L -o index.html https://huggingface.co/spaces/cliqtomedia/apify-web-scraper/resolve/main/index.html
29 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>Apify Web Scraper</title> | |
| <style> | |
| :root{--bg:#fff;--fg:#1f2330;--muted:#5d6475;--line:#d9dce4;--card:#f6f7fa;--accent:#5b4bdb;--accent-soft:#ecebfc;--err:#b42318;--ok:#067647} | |
| @media (prefers-color-scheme:dark){:root{--bg:#0f1117;--fg:#e8eaf0;--muted:#a3a9b8;--line:#2c3140;--card:#171a23;--accent:#8b7ff0;--accent-soft:#25223f;--err:#ff8a80;--ok:#6ce9a6}} | |
| *{box-sizing:border-box} | |
| body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif} | |
| main{max-width:860px;margin:0 auto;padding:24px 16px 48px} | |
| h1{font-size:1.6rem;margin:0 0 4px} | |
| h2{font-size:1.15rem;margin:28px 0 8px} | |
| p.lead{color:var(--muted);margin:0 0 20px} | |
| label{display:block;font-weight:600;margin:14px 0 6px} | |
| .help{display:block;color:var(--muted);font-weight:400;font-size:.86rem;margin-top:2px} | |
| small{color:var(--muted);font-weight:400} | |
| input,textarea,select{width:100%;padding:10px 12px;border:1px solid var(--line);border-radius:8px;background:var(--card);color:var(--fg);font:inherit} | |
| input[type=checkbox]{width:auto;margin-right:8px;vertical-align:middle} | |
| textarea{min-height:84px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem} | |
| .row{display:flex;gap:12px;flex-wrap:wrap}.row>div{flex:1 1 200px} | |
| button{padding:11px 18px;border:0;border-radius:8px;background:var(--accent);color:#fff;font:inherit;font-weight:600;cursor:pointer} | |
| button[disabled]{opacity:.6;cursor:wait} | |
| button.sec{background:transparent;color:var(--accent);border:1px solid var(--accent)} | |
| .actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:18px} | |
| #status,#tokenStatus{margin-top:12px;color:var(--muted)}.err{color:var(--err)}.ok{color:var(--ok)} | |
| .steps{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px 16px;margin:0 0 8px} | |
| .steps ol{margin:6px 0 0;padding-left:20px} | |
| #list{margin-top:10px;max-height:320px;overflow-y:auto;border:1px solid var(--line);border-radius:10px} | |
| #list button{display:block;width:100%;text-align:left;background:transparent;color:var(--fg);border:0;border-bottom:1px solid var(--line);border-radius:0;padding:10px 12px;font-weight:400} | |
| #list button:last-child{border-bottom:0} | |
| #list button:hover,#list button.sel{background:var(--accent-soft)} | |
| #list b{display:block} | |
| #list span{display:block;color:var(--muted);font-size:.85rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| #picked{margin-top:16px;padding:12px 16px;border:1px solid var(--accent);border-radius:10px} | |
| #picked p{margin:4px 0 0;color:var(--muted);font-size:.92rem} | |
| .opts label{font-weight:400;margin:4px 0} | |
| details{margin-top:16px;border:1px solid var(--line);border-radius:10px;padding:8px 14px} | |
| summary{cursor:pointer;font-weight:600} | |
| pre{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:10px;overflow-x:auto;font-size:.82rem} | |
| .tablewrap{margin-top:12px;overflow-x:auto;border:1px solid var(--line);border-radius:10px} | |
| table{border-collapse:collapse;width:100%;font-size:.88rem} | |
| th,td{padding:8px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top;min-width:110px} | |
| .c.wide{min-width:240px} | |
| .c{max-width:300px;max-height:7.6em;overflow:hidden;overflow-wrap:anywhere} | |
| td.num{white-space:nowrap;text-align:right;min-width:0} | |
| th{background:var(--card);white-space:nowrap} | |
| tr:last-child td{border-bottom:0} | |
| a{color:var(--accent)} | |
| .note{background:var(--accent-soft);border-radius:10px;padding:10px 14px;margin:16px 0} | |
| footer{margin-top:32px;color:var(--muted);font-size:.9rem} | |
| </style> | |
| </head> | |
| <body> | |
| <main> | |
| <h1 id="title"></h1> | |
| <p class="lead" id="lead"></p> | |
| <p class="note" id="crossLink" hidden></p> | |
| <div class="steps"><strong>Your Apify token (once)</strong> | |
| <ol> | |
| <li>Sign up or log in at <a href="https://console.apify.com" target="_blank" rel="noopener noreferrer">console.apify.com</a> (the free plan works).</li> | |
| <li>Open <b>Settings → API & Integrations</b> and copy your personal API token (<a href="https://docs.apify.com/platform/integrations/api#api-token" target="_blank" rel="noopener noreferrer">how to find it</a>).</li> | |
| <li>Paste it below. It stays in this tab, goes only to api.apify.com and is never saved.</li> | |
| </ol></div> | |
| <label for="token">Apify API token</label> | |
| <input id="token" type="password" autocomplete="off" spellcheck="false" placeholder="Paste your own token"> | |
| <div class="actions"><button class="sec" id="checkToken" type="button">Check token</button></div> | |
| <div id="tokenStatus" role="status"></div> | |
| <h2 id="pickTitle">1. Choose a scraper</h2> | |
| <div class="row"> | |
| <div><label for="q">Search</label><input id="q" type="search" placeholder="e.g. reddit, jobs, amazon, markdown"></div> | |
| <div id="catBox"><label for="cat">Category</label><select id="cat"><option value="">All categories</option></select></div> | |
| </div> | |
| <div id="list" role="listbox" aria-label="Scrapers"></div> | |
| <div id="catalogStatus" class="help"></div> | |
| <div id="formBox" hidden> | |
| <div id="picked"></div> | |
| <h2>2. Input</h2> | |
| <div id="mainFields"></div> | |
| <details id="advBox"><summary>More options</summary><div id="advFields"></div></details> | |
| <h2>3. Run</h2> | |
| <div class="row"> | |
| <div><label for="maxItems">Max results <span class="help">The run stops after this many results.</span></label><input id="maxItems" type="number" min="1" max="10000" value="20"></div> | |
| <div><label for="maxCharge">Max cost, USD <span class="help">Spending cap for this run on your account.</span></label><input id="maxCharge" type="number" min="0.1" step="0.1" value="1"></div> | |
| </div> | |
| <div class="actions"><button id="run" type="button">Run</button><button class="sec" id="abort" type="button" hidden>Stop run</button></div> | |
| <div id="status" role="status"></div> | |
| <div class="actions" id="tools" hidden><button class="sec" id="dlCsv" type="button">Download CSV</button><button class="sec" id="dlJson" type="button">Download JSON</button></div> | |
| <div id="out"></div> | |
| <details><summary>Run the same from code (Python, curl)</summary><pre id="code"></pre></details> | |
| </div> | |
| <footer> | |
| Runs are billed to your own Apify account at each Actor's price. | |
| <span id="footerLinks"></span> | |
| </footer> | |
| </main> | |
| <script> | |
| // ---- Space settings. Bundles change only this block. ---- | |
| const CONFIG = { | |
| title: 'Apify Web Scraper', | |
| lead: 'One page for 250+ ready scrapers by Cliqto Media: Reddit, YouTube transcripts, Google, Amazon, jobs, reviews, real estate, website to Markdown and more. Pick a scraper, fill the form, get a table or JSON. Runs on Apify with your own token.', | |
| actors: null, // null = all our Actors; or a list of Actor names for a bundle | |
| universal: null, // link to the universal Space, shown in bundles | |
| pick: null, // Actor opened on load (the #name in the address wins) | |
| space: 'apify-web-scraper' | |
| }; | |
| // --------------------------------------------------------- | |
| const API = 'https://api.apify.com/v2', OWNER = 'cliqtomedia'; | |
| const HIDDEN = /onlyfans|adult|nsfw|social-video-downloader/i; | |
| const UTM = 'utm_source=huggingface&utm_medium=template&utm_campaign=promo-2026-11&utm_content=' + CONFIG.space; | |
| const SITE = 'https://cliqtomedia.com'; | |
| const DEFAULT_LIMIT = 20; | |
| const $ = id => document.getElementById(id); | |
| let catalog = [], current = null, lastName = '', fields = [], lastItems = [], runId = null, stopRequested = false; | |
| function el(tag, attrs, text){ const e = document.createElement(tag); if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]); if (text !== undefined) e.textContent = text; return e; } | |
| function link(href, text){ const a = el('a', {href, target:'_blank', rel:'noopener noreferrer'}, text); return a; } | |
| function siteUrl(name){ return SITE + (name ? '/actors/' + encodeURIComponent(name) + '/' : '/') + '?' + UTM; } | |
| function setMsg(node, msg, cls){ node.textContent = msg; node.className = cls || ''; } | |
| function token(){ return $('token').value.trim(); } | |
| async function call(path, opts = {}, tok){ | |
| const headers = {}; | |
| if (opts.body) headers['Content-Type'] = 'application/json'; | |
| if (tok) headers['Authorization'] = 'Bearer ' + tok; | |
| const r = await fetch(API + path, {method: opts.method || 'GET', headers, body: opts.body}); | |
| const text = await r.text(); | |
| let json = null; try { json = text ? JSON.parse(text) : null; } catch (e) {} | |
| if (!r.ok){ | |
| let msg = (json && json.error && json.error.message) || ('Apify API error ' + r.status); | |
| if (r.status === 401) msg = 'Apify did not accept the token. Copy it again from Apify Console → Settings → API & Integrations.'; | |
| const err = new Error(msg); err.status = r.status; throw err; | |
| } | |
| return json; | |
| } | |
| // ---- header, links ---- | |
| $('title').textContent = CONFIG.title; document.title = CONFIG.title; | |
| $('lead').textContent = CONFIG.lead; | |
| if (CONFIG.universal){ | |
| const p = $('crossLink'); p.hidden = false; | |
| p.append('Need another site? The ', link(CONFIG.universal, 'Apify Web Scraper'), ' Space runs any of our 250+ scrapers with the same token.'); | |
| } | |
| $('footerLinks').append(' All scrapers and prices: ', link(siteUrl(), 'Cliqto Media'), '.'); | |
| // ---- token check ---- | |
| $('checkToken').onclick = async () => { | |
| const t = token(); const s = $('tokenStatus'); | |
| if (!t){ setMsg(s, 'Paste your own Apify API token first.', 'err'); return; } | |
| setMsg(s, 'Checking…'); | |
| try { | |
| const me = await call('/users/me', {}, t); | |
| const d = me.data || {}; | |
| setMsg(s, 'Token works. Apify account: ' + (d.username || 'your account') + (d.plan && d.plan.id ? ' (plan ' + d.plan.id + ')' : '') + '. Runs start only when you press Run.', 'ok'); | |
| } catch (e){ setMsg(s, e.message, 'err'); } | |
| }; | |
| // ---- catalog ---- | |
| async function loadCatalog(){ | |
| setMsg($('catalogStatus'), 'Loading scrapers…'); | |
| const out = []; | |
| for (let offset = 0; offset < 2000; offset += 200){ | |
| const page = await call('/store?username=' + OWNER + '&limit=200&offset=' + offset); | |
| for (const a of page.data.items){ | |
| if (a.username !== OWNER || HIDDEN.test(a.name) || HIDDEN.test(a.title || '')) continue; | |
| out.push({name: a.name, title: a.title || a.name, description: a.description || '', categories: a.categories || [], users: (a.stats && a.stats.totalUsers) || 0}); | |
| } | |
| if (offset + 200 >= page.data.total) break; | |
| } | |
| catalog = out; | |
| if (CONFIG.actors){ | |
| const order = new Map(CONFIG.actors.map((n, i) => [n, i])); | |
| catalog = catalog.filter(a => order.has(a.name)).sort((a, b) => order.get(a.name) - order.get(b.name)); | |
| } else { | |
| catalog.sort((a, b) => b.users - a.users || a.title.localeCompare(b.title)); | |
| } | |
| const cats = [...new Set(catalog.flatMap(a => a.categories))].sort(); | |
| if (cats.length < 2 || CONFIG.actors) $('catBox').hidden = true; | |
| for (const c of cats) $('cat').append(el('option', {value: c}, c.charAt(0) + c.slice(1).toLowerCase().replace(/_/g, ' '))); | |
| setMsg($('catalogStatus'), catalog.length + ' scrapers. Data comes from the public Apify Store.'); | |
| renderList(); | |
| const want = hashName() || CONFIG.pick || (CONFIG.actors ? CONFIG.actors[0] : ''); | |
| if (want && catalog.some(a => a.name === want)) pick(want, false); | |
| } | |
| function renderList(){ | |
| const q = $('q').value.trim().toLowerCase().split(/\s+/).filter(Boolean); | |
| const cat = $('cat').value; | |
| const list = $('list'); list.textContent = ''; | |
| const shown = catalog.filter(a => (!cat || a.categories.includes(cat)) && q.every(w => (a.title + ' ' + a.name + ' ' + a.description).toLowerCase().includes(w))); | |
| for (const a of shown){ | |
| const b = el('button', {type: 'button', role: 'option', 'data-name': a.name}); | |
| if (current && current.name === a.name) b.className = 'sel'; | |
| b.append(el('b', null, a.title), el('span', null, a.description)); | |
| b.onclick = () => pick(a.name, true); | |
| list.append(b); | |
| } | |
| if (!shown.length) list.append(el('div', {class: 'help', style: 'padding:10px 12px'}, 'Nothing found. Try another word.')); | |
| } | |
| $('q').oninput = renderList; $('cat').onchange = renderList; | |
| // ---- schema → form ---- | |
| const LIMIT_WORD = new Set(['max','limit','count','number','num','top','total']); | |
| const LIMIT_NOUN = /^(item|result|row|review|post|video|job|product|comment|listing|article|story|stories|tweet|profile|lead|place|record|page|hotel|compan|channel|episode|question|answer|repo|event|offer|ad|image|stream|short|track|book|domain|keyword|url|link|entr|snapshot|filing|award|propert|car|vehicle|deal|app|game|movie|show)/; | |
| const NOT_LIMIT = new Set(['price','retry','retries','concurrency','age','days','day','size','depth','timeout','memory','length','chars','words','rating','score','year','years','distance','radius','delay','seconds','ms','bytes','minutes','impressions','viewers','followers','salary','budget']); | |
| function words(k){ return k.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z]+/).filter(Boolean); } | |
| function isLimitKey(k){ | |
| const w = words(k); | |
| if (w.some(x => NOT_LIMIT.has(x))) return false; | |
| if (w.length === 1) return ['limit','max','count','maxitems'].includes(w[0]); | |
| return w.some(x => LIMIT_WORD.has(x)) && w.some(x => !LIMIT_WORD.has(x) && LIMIT_NOUN.test(x)); | |
| } | |
| function strip(html){ const d = new DOMParser().parseFromString(String(html || ''), 'text/html'); return (d.body.textContent || '').replace(/\s+/g, ' ').trim(); } | |
| function hashName(){ try { return decodeURIComponent(location.hash.slice(1)); } catch (e){ return ''; } } | |
| function clip(s, n){ return s.length <= n ? s : s.slice(0, s.lastIndexOf(' ', n)) + '…'; } | |
| function kindOf(p){ | |
| if (p.editor === 'proxy' || p.editor === 'json' || p.editor === 'keyValue') return 'json'; | |
| if (p.type === 'boolean') return 'boolean'; | |
| if (p.type === 'integer' || p.type === 'number') return 'number'; | |
| if (p.type === 'string') return p.enum && p.enum.length ? 'select' : (/textarea|javascript|python/.test(p.editor || '') ? 'textarea' : 'text'); | |
| if (p.type === 'array'){ | |
| if (p.items && p.items.enum && p.items.enum.length) return 'multiselect'; | |
| if (p.editor === 'requestListSources' || p.editor === 'requestList') return 'urls'; | |
| if (p.editor === 'stringList' || (p.items && p.items.type === 'string') || (!p.editor && !p.items)) return 'list'; | |
| } | |
| return 'json'; | |
| } | |
| function buildFields(schema){ | |
| const req = new Set(schema.required || []); | |
| let inAdv = false; const out = []; | |
| for (const [key, p] of Object.entries(schema.properties || {})){ | |
| if (p.isSecret) continue; | |
| if (p.sectionCaption && /advanced|proxy|developer|debug|optional/i.test(p.sectionCaption)) inAdv = true; | |
| const kind = kindOf(p); | |
| const start = p.prefill !== undefined ? p.prefill : p.default; | |
| const f = {key, p, kind, label: p.title || key, help: clip(strip(p.description), 220), required: req.has(key), isLimit: kind === 'number' && isLimitKey(key), start}; | |
| const adv = !f.required && (inAdv || p.editor === 'proxy' || /debug|proxy|cookie|session|concurrency|timeout|webhook/i.test(key)); | |
| f.main = !adv && (f.required || p.prefill !== undefined || f.isLimit); | |
| out.push(f); | |
| } | |
| if (!out.some(f => f.main)) out.forEach(f => f.main = !/debug|proxy|cookie|session|concurrency|timeout|webhook/i.test(f.key)); | |
| return out; | |
| } | |
| function startValue(f){ | |
| let v = f.start; | |
| if (f.isLimit){ | |
| const min = f.p.minimum || 1, max = f.p.maximum || DEFAULT_LIMIT; | |
| if (typeof v !== 'number' || v === 0 || v > DEFAULT_LIMIT) v = Math.max(min, Math.min(DEFAULT_LIMIT, max)); | |
| } | |
| return v; | |
| } | |
| function renderField(f){ | |
| const box = el('div'); const id = 'f_' + f.key; | |
| const lab = el('label', {for: id}, f.label + (f.required ? ' *' : '')); | |
| const v = startValue(f); | |
| let input; | |
| if (f.kind === 'boolean'){ | |
| input = el('input', {id, type: 'checkbox'}); input.checked = v === true; | |
| lab.textContent = ''; lab.append(input, f.label); | |
| box.append(lab); | |
| } else { | |
| box.append(lab); | |
| if (f.kind === 'select'){ | |
| input = el('select', {id}); | |
| if (!f.required) input.append(el('option', {value: ''}, '(default)')); | |
| (f.p.enum || []).forEach((o, i) => input.append(el('option', {value: String(o)}, String((f.p.enumTitles || [])[i] || o)))); | |
| if (v !== undefined) input.value = String(v); | |
| } else if (f.kind === 'multiselect'){ | |
| input = el('div', {id, class: 'opts'}); | |
| const sel = new Set(Array.isArray(v) ? v.map(String) : []); | |
| (f.p.items.enum || []).forEach((o, i) => { const l = el('label'); const c = el('input', {type: 'checkbox', value: String(o)}); c.checked = sel.has(String(o)); l.append(c, String((f.p.items.enumTitles || [])[i] || o)); input.append(l); }); | |
| } else if (f.kind === 'number'){ | |
| input = el('input', {id, type: 'number'}); | |
| if (f.p.minimum !== undefined) input.min = f.p.minimum; | |
| if (f.p.maximum !== undefined) input.max = f.p.maximum; | |
| if (typeof v === 'number') input.value = v; | |
| } else if (f.kind === 'list' || f.kind === 'urls'){ | |
| input = el('textarea', {id, rows: '3'}); | |
| input.value = Array.isArray(v) ? v.map(x => typeof x === 'object' && x ? (x.url || JSON.stringify(x)) : String(x)).join('\n') : ''; | |
| f.help = (f.help ? f.help + ' ' : '') + 'One per line.'; | |
| } else if (f.kind === 'json'){ | |
| input = el('textarea', {id, rows: '3'}); input.value = v === undefined ? '' : JSON.stringify(v, null, 2); | |
| f.help = (f.help ? f.help + ' ' : '') + 'JSON.'; | |
| } else { | |
| input = el(f.kind === 'textarea' ? 'textarea' : 'input', {id, type: 'text'}); input.value = v === undefined || v === null ? '' : String(v); | |
| } | |
| box.append(input); | |
| } | |
| if (f.help) box.append(el('span', {class: 'help'}, f.help)); | |
| input.addEventListener('input', showCode); input.addEventListener('change', showCode); | |
| return box; | |
| } | |
| function readInput(strict){ | |
| const input = {}, missing = []; | |
| for (const f of fields){ | |
| const node = $('f_' + f.key); let v; | |
| if (f.kind === 'boolean'){ v = node.checked; if (!f.required && v === (f.p.default === true) && f.start === undefined) v = undefined; } | |
| else if (f.kind === 'multiselect'){ v = [...node.querySelectorAll('input:checked')].map(c => c.value); } | |
| else if (f.kind === 'number'){ v = node.value === '' ? undefined : Number(node.value); } | |
| else if (f.kind === 'list'){ v = node.value.split('\n').map(s => s.trim()).filter(Boolean); } | |
| else if (f.kind === 'urls'){ v = node.value.split('\n').map(s => s.trim()).filter(Boolean).map(url => ({url})); } | |
| else if (f.kind === 'json'){ | |
| if (node.value.trim() === '') v = undefined; | |
| else { try { v = JSON.parse(node.value); } catch (e){ if (strict) throw new Error('“' + f.label + '” is not valid JSON.'); v = undefined; } } | |
| } | |
| else { v = node.value; if (f.kind === 'select' && v !== '' && f.p.type !== 'string') v = JSON.parse(v); } | |
| const empty = v === undefined || v === '' || (Array.isArray(v) && v.length === 0); | |
| if (empty){ if (f.required) missing.push(f.label); continue; } | |
| input[f.key] = v; | |
| } | |
| if (strict && missing.length) throw new Error('Fill in: ' + missing.join(', ') + '.'); | |
| return input; | |
| } | |
| function py(v, ind){ | |
| if (v === null || v === undefined) return 'None'; | |
| if (v === true) return 'True'; if (v === false) return 'False'; | |
| if (typeof v === 'number' || typeof v === 'string') return JSON.stringify(v); | |
| const n = ind + ' '; | |
| if (Array.isArray(v)) return v.length ? '[\n' + v.map(x => n + py(x, n)).join(',\n') + '\n' + ind + ']' : '[]'; | |
| const k = Object.keys(v); | |
| return k.length ? '{\n' + k.map(x => n + JSON.stringify(x) + ': ' + py(v[x], n)).join(',\n') + '\n' + ind + '}' : '{}'; | |
| } | |
| function showCode(){ | |
| if (!current) return; | |
| let input = {}; try { input = readInput(false); } catch (e) {} | |
| const id = OWNER + '~' + current.name; | |
| const max = parseInt($('maxItems').value, 10) || DEFAULT_LIMIT, charge = parseFloat($('maxCharge').value) || 1; | |
| $('code').textContent = | |
| '# pip install apify-client\nfrom apify_client import ApifyClient\n\nclient = ApifyClient("YOUR_APIFY_TOKEN")\n' + | |
| 'run = client.actor("' + OWNER + '/' + current.name + '").call(\n run_input=' + py(input, ' ') + ',\n max_items=' + max + ',\n max_total_charge_usd=' + charge + ',\n)\n' + | |
| 'items = client.dataset(run["defaultDatasetId"]).list_items().items\n\n' + | |
| '# curl\ncurl -X POST "https://api.apify.com/v2/acts/' + id + '/run-sync-get-dataset-items?maxItems=' + max + '&maxTotalChargeUsd=' + charge + '" \\\n -H "Authorization: Bearer YOUR_APIFY_TOKEN" -H "Content-Type: application/json" \\\n -d \'' + JSON.stringify(input).replace(/'/g, "'\\''") + '\''; | |
| } | |
| $('maxItems').oninput = showCode; $('maxCharge').oninput = showCode; | |
| async function pick(name, userClick){ | |
| if (userClick && current && current.name === name) return; | |
| if (runId || $('run').disabled){ setMsg($('status'), 'A run is in progress. Wait for it or press Stop run, then pick another scraper.', 'err'); return; } | |
| const a = catalog.find(x => x.name === name); if (!a) return; | |
| current = a; renderList(); | |
| history.replaceState(null, '', '#' + name); | |
| $('formBox').hidden = false; $('out').textContent = ''; $('tools').hidden = true; setMsg($('status'), ''); | |
| const pk = $('picked'); pk.textContent = ''; | |
| pk.append(el('b', null, a.title), el('p', null, a.description)); | |
| const more = el('p'); more.append('Price, examples and docs: ', link(siteUrl(name), 'Actor page'), '.'); pk.append(more); | |
| $('mainFields').textContent = 'Loading form…'; $('advFields').textContent = ''; | |
| try { | |
| const act = await call('/acts/' + OWNER + '~' + encodeURIComponent(name)); | |
| if (!act.data || act.data.username !== OWNER) throw new Error('This page runs only Cliqto Media Actors.'); | |
| const build = await call('/acts/' + OWNER + '~' + encodeURIComponent(name) + '/builds/default'); | |
| const schema = build.data && build.data.inputSchema ? JSON.parse(build.data.inputSchema) : {properties: {}}; | |
| if (current !== a) return; | |
| fields = buildFields(schema); | |
| $('mainFields').textContent = ''; | |
| for (const f of fields) (f.main ? $('mainFields') : $('advFields')).append(renderField(f)); | |
| $('advBox').hidden = !fields.some(f => !f.main); | |
| if (!fields.length) $('mainFields').append(el('p', {class: 'help'}, 'This Actor needs no input.')); | |
| showCode(); | |
| if (userClick) $('picked').scrollIntoView({behavior: 'smooth', block: 'start'}); | |
| } catch (e){ if (current !== a) return; $('mainFields').textContent = ''; $('mainFields').append(el('p', {class: 'err'}, 'Could not load the form: ' + e.message)); } | |
| } | |
| // ---- run ---- | |
| async function poll(id, t){ | |
| for (let i = 0; ; i++){ | |
| try { return await call('/actor-runs/' + id + '?waitForFinish=10', {}, t); } | |
| catch (e){ if (i >= 4) throw new Error(e.message + ' The run may still be going: check it in Apify Console (Actors → Runs).'); await new Promise(r => setTimeout(r, 3000)); } | |
| } | |
| } | |
| const TERMINAL = new Set(['SUCCEEDED','FAILED','ABORTED','TIMED-OUT']); | |
| $('run').onclick = async () => { | |
| const t = token(); const s = $('status'); | |
| if (!t){ setMsg(s, 'Paste your own Apify API token first (top of the page).', 'err'); $('token').focus(); return; } | |
| let input; try { input = readInput(true); } catch (e){ setMsg(s, e.message, 'err'); return; } | |
| const max = Math.max(1, Math.min(10000, parseInt($('maxItems').value, 10) || DEFAULT_LIMIT)); | |
| const charge = Math.max(0.1, parseFloat($('maxCharge').value) || 1); | |
| $('run').disabled = true; $('abort').hidden = false; stopRequested = false; | |
| $('out').textContent = ''; $('tools').hidden = true; setMsg(s, 'Starting the run on Apify…'); | |
| try { | |
| let run = (await call('/acts/' + OWNER + '~' + encodeURIComponent(current.name) + '/runs?maxItems=' + max + '&maxTotalChargeUsd=' + charge, {method: 'POST', body: JSON.stringify(input)}, t)).data; | |
| runId = run.id; | |
| const started = Date.now(); | |
| while (!TERMINAL.has(run.status)){ | |
| if (stopRequested){ await call('/actor-runs/' + run.id + '/abort', {method: 'POST'}, t).catch(() => {}); } | |
| setMsg(s, 'Running… ' + Math.round((Date.now() - started) / 1000) + ' s' + (run.stats && run.stats.itemCount ? ', ' + run.stats.itemCount + ' results so far' : '') + '. You can leave this tab open.'); | |
| run = (await poll(run.id, t)).data; | |
| } | |
| const items = await call('/datasets/' + run.defaultDatasetId + '/items?clean=true&format=json&limit=' + max, {}, t); | |
| render(Array.isArray(items) ? items.filter(x => x && typeof x === 'object') : [], run); | |
| } catch (e){ setMsg(s, e.message, 'err'); } | |
| finally { $('run').disabled = false; $('abort').hidden = true; runId = null; } | |
| }; | |
| $('abort').onclick = () => { stopRequested = true; setMsg($('status'), 'Stopping the run…'); }; | |
| const KEY_COLS = [/^(title|name|fullName|headline)$/i, /^(text|description|content|markdown|transcript|body|snippet|review(Text)?)$/i, /price|amount|salary/i, /rating|score|likes|stars/i, /^(url|link|jobUrl|postUrl|productUrl|pageUrl)$/i, /(date|time|At)$/, /company|author|user(name)?|channel|seller|subreddit|location|city|country/i, /^(email|phone|domain|status)$/i]; | |
| function shortText(v){ | |
| if (v && typeof v === 'object' && !Array.isArray(v)) return String(v.name || v.title || v.username || v.fullName || v.url || JSON.stringify(v)); | |
| if (Array.isArray(v)) return v.map(x => x && typeof x === 'object' ? (x.name || x.title || x.url || JSON.stringify(x)) : String(x)).join(', '); | |
| return cellText(v); | |
| } | |
| function cellText(v){ if (v === null || v === undefined) return ''; return typeof v === 'object' ? JSON.stringify(v) : String(v); } | |
| function columns(items, all){ | |
| const seen = new Map(); | |
| for (const it of (all ? items : items.slice(0, 100))) for (const k of Object.keys(it)) seen.set(k, (seen.get(k) || 0) + 1); | |
| return [...seen.keys()]; | |
| } | |
| function render(items, run){ | |
| const s = $('status'); const out = $('out'); | |
| const runLink = 'https://console.apify.com/actors/runs/' + run.id; | |
| if (!items.length){ | |
| s.textContent = ''; s.className = 'err'; | |
| s.append('The run ended (' + run.status + ') with no results' + (run.statusMessage ? ': ' + run.statusMessage : '') + '. ', link(runLink, 'Open the run in Apify'), '.'); | |
| return; | |
| } | |
| lastItems = items; lastName = current.name; | |
| const cols = columns(items); | |
| const filled = cols.filter(c => items.slice(0, 100).some(it => { const v = it[c]; return v !== null && v !== undefined && v !== '' && !(Array.isArray(v) && !v.length); })); | |
| const rank = c => { const i = KEY_COLS.findIndex(r => r.test(c)); return i < 0 ? 99 : i; }; | |
| const top = new Set([...filled].sort((a, b) => rank(a) - rank(b)).slice(0, 10)); | |
| const shown = filled.filter(c => top.has(c)); | |
| s.textContent = ''; s.className = run.status === 'SUCCEEDED' ? 'ok' : ''; | |
| s.append('Done: ' + items.length + ' result(s)' + (run.status !== 'SUCCEEDED' ? ' (run ' + run.status.toLowerCase() + ')' : '') + '. ' + (cols.length > shown.length ? 'Table shows ' + shown.length + ' of ' + cols.length + ' columns; downloads have all. ' : ''), link(runLink, 'Run and cost in Apify'), '.'); | |
| const wrap = el('div', {class: 'tablewrap'}); const table = el('table'); | |
| const head = table.createTHead().insertRow(); | |
| shown.forEach(c => head.append(el('th', null, c))); | |
| const body = table.createTBody(); | |
| items.slice(0, 200).forEach(it => { | |
| const tr = body.insertRow(); | |
| shown.forEach(c => { | |
| const td = tr.insertCell(); const v = it[c]; | |
| if (typeof v === 'string' && /^https:\/\/[^\s"'<>]+$/.test(v)){ td.append(link(v, 'open')); } | |
| else if (typeof v === 'number' || typeof v === 'boolean'){ td.textContent = String(v); td.className = 'num'; } | |
| else td.append(el('div', {class: shortText(v).length > 60 ? 'c wide' : 'c', title: clip(cellText(v), 1000)}, clip(shortText(v), 240))); | |
| }); | |
| }); | |
| wrap.append(table); out.append(wrap); | |
| if (items.length > 200) out.append(el('p', {class: 'help'}, 'Showing the first 200 rows. Downloads have all ' + items.length + '.')); | |
| $('tools').hidden = false; | |
| } | |
| function csvCell(v){ const str = typeof v === 'string'; v = cellText(v); if (str && /^[=+\-@\t\r]/.test(v)) v = "'" + v; return /[",\n\r]/.test(v) ? '"' + v.replace(/"/g, '""') + '"' : v; } | |
| function download(name, text, type){ | |
| const a = document.createElement('a'); | |
| a.href = URL.createObjectURL(new Blob([text], {type})); a.download = name; a.style.display = 'none'; document.body.append(a); a.click(); a.remove(); | |
| setTimeout(() => URL.revokeObjectURL(a.href), 1000); | |
| } | |
| $('dlCsv').onclick = () => { const cols = columns(lastItems, true); download(lastName + '.csv', '\uFEFF' + [cols.map(csvCell).join(',')].concat(lastItems.map(it => cols.map(c => csvCell(it[c])).join(','))).join('\n'), 'text/csv'); }; | |
| $('dlJson').onclick = () => download(lastName + '.json', JSON.stringify(lastItems, null, 2), 'application/json'); | |
| window.addEventListener('hashchange', () => { const n = hashName(); if (n && (!current || n !== current.name)) pick(n, true); }); | |
| loadCatalog().catch(e => setMsg($('catalogStatus'), 'Could not load the list of scrapers: ' + e.message, 'err')); | |
| </script> | |
| </body> | |
| </html> | |