fix(bloomberg): avoid collection timeouts

This commit is contained in:
2026-11-24 09:41:26 +01:00
parent d129af0d56
commit 1981018ae1
11 changed files with 641 additions and 73 deletions

View File

@ -1,4 +1,4 @@
const { withPublicationDates } = require('./publication-date')
const { withDatesFromLoadedHtml } = require('./publication-date')
const express = require('express')
const cheerio = require('cheerio')
const puppeteer = require('puppeteer-extra')
@ -21,21 +21,24 @@ async function byparrRequest(body) {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!resp.ok) throw new Error(`byparr HTTP ${resp.status}: ${await resp.text()}`)
if (!resp.ok) {
try { await resp.body?.cancel() } catch { /* Release without reading/logging the body. */ }
throw new Error(`byparr HTTP ${resp.status}`)
}
return resp.json()
}
async function byparrFetch(url, quiet = false) {
if (!quiet) console.log('[byparr] GET', url)
if (!quiet) console.log('[byparr] section request')
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: 60000 })
const html = data.solution?.response
if (!html) throw new Error(`byparr returned no HTML for ${url}`)
if (!html) throw new Error('byparr returned no HTML')
return { html }
}
// ---------- Article parsing ----------
function parseArticlesFromHtml(html) {
function parseArticlesFromHtml(html, loadedURL) {
const $ = cheerio.load(html)
const results = []
const seen = new Set()
@ -56,7 +59,7 @@ function parseArticlesFromHtml(html) {
results.push({ title, url: clean })
})
return results
return withDatesFromLoadedHtml(results, html, loadedURL, $)
}
// ---------- Bloomberg scraping via Byparr ----------
@ -81,20 +84,23 @@ async function scrapeBloombergViaByparr(username, password) {
for (const url of byparrPages) {
try {
const { html } = await byparrFetch(url)
const items = parseArticlesFromHtml(html)
const items = parseArticlesFromHtml(html, url)
for (const item of items) {
if (!seen.has(item.url)) {
seen.add(item.url)
articles.push(item)
} else if (item.published_at) {
const existing = articles.find(article => article.url === item.url)
if (existing && !existing.published_at) existing.published_at = item.published_at
}
}
console.log('[bloomberg]', url, '->', items.length, 'articles')
console.log('[bloomberg] section articles:', items.length)
} catch (e) {
console.error('[bloomberg] error on', url, ':', e.message)
console.error('[bloomberg] section unavailable')
}
}
return withPublicationDates(articles, async url => (await byparrFetch(url, true)).html)
return articles
}
// ---------- Bloomberg scraping via Puppeteer (fallback, may be blocked) ----------
@ -161,8 +167,8 @@ async function scrapeBloombergViaPuppeteer(username, password) {
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
}))
)
console.log('[bloomberg] inputs on login page:', JSON.stringify(pageInputs))
console.log('[bloomberg] page title:', await page.title())
console.log('[bloomberg] login input count:', pageInputs.length)
const emailOk = await tryType(page, [
'#email-form-input',
@ -194,7 +200,7 @@ async function scrapeBloombergViaPuppeteer(username, password) {
} catch {
await new Promise(r => setTimeout(r, 3000))
}
console.log('[bloomberg] after email submit, url:', page.url())
console.log('[bloomberg] email step completed')
const pwdOk = await tryType(page, [
'input[type="password"]',
@ -211,10 +217,9 @@ async function scrapeBloombergViaPuppeteer(username, password) {
])
const currentURL = page.url()
console.log('[bloomberg] after login, url:', currentURL)
console.log('[bloomberg] login navigation completed')
if (currentURL.includes('/account/signin')) {
const bodyText = await page.evaluate(() => document.body.innerText.slice(0, 500))
throw new Error(`login did not redirect — page content: ${bodyText}`)
throw new Error('login did not redirect')
}
const targetPages = [
@ -228,29 +233,29 @@ async function scrapeBloombergViaPuppeteer(username, password) {
for (const url of targetPages) {
try {
console.log('[bloomberg] scraping', url)
console.log('[bloomberg] loading section')
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
await page.waitForSelector('a[data-component="story-link"]', { timeout: 15000 }).catch(() => {})
const html = await page.content()
const items = parseArticlesFromHtml(html)
const items = parseArticlesFromHtml(html, url)
for (const item of items) {
if (!seen.has(item.url)) {
seen.add(item.url)
articles.push(item)
} else if (item.published_at) {
const existing = articles.find(article => article.url === item.url)
if (existing && !existing.published_at) existing.published_at = item.published_at
}
}
console.log('[bloomberg]', url, '->', items.length, 'articles')
console.log('[bloomberg] section articles:', items.length)
} catch (e) {
console.error('[bloomberg] error on', url, ':', e.message)
console.error('[bloomberg] section unavailable')
}
}
return await withPublicationDates(articles, async url => {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
return page.content()
})
return articles
} finally {
if (browser) await browser.close()
}
@ -279,8 +284,8 @@ app.post('/bloomberg/scrape', async (req, res) => {
console.log('[bloomberg] total:', articles.length, 'articles')
res.json({ articles })
} catch (e) {
console.error('[bloomberg] scrape error:', e.message)
res.status(500).json({ error: e.message })
console.error('[bloomberg] scrape unavailable')
res.status(500).json({ error: 'scrape unavailable' })
}
})