fix(scraper): harden Bloomberg login state (#40)
This commit is contained in:
@ -1,5 +1,6 @@
|
||||
const { enrichArticles, canonicalURL, TOTAL_TIMEOUT_MS } = require('./article-content')
|
||||
const { withDatesFromLoadedHtml } = require('./publication-date')
|
||||
const { inspectLoginState, classifyLoginState, authenticatedDestination, trustedLoginOrigin, typeVisibleInput, submitInputForm } = require('./bloomberg-login')
|
||||
const express = require('express')
|
||||
const cheerio = require('cheerio')
|
||||
const puppeteer = require('puppeteer-extra')
|
||||
@ -123,28 +124,6 @@ function launchBrowser() {
|
||||
})
|
||||
}
|
||||
|
||||
async function tryClick(page, selectors) {
|
||||
for (const sel of selectors) {
|
||||
try {
|
||||
const el = await page.$(sel)
|
||||
if (el) { await el.click(); return true }
|
||||
} catch {}
|
||||
}
|
||||
await page.keyboard.press('Enter')
|
||||
return false
|
||||
}
|
||||
|
||||
async function tryType(page, selectors, text) {
|
||||
for (const sel of selectors) {
|
||||
try {
|
||||
await page.waitForSelector(sel, { timeout: 4000 })
|
||||
await page.type(sel, text, { delay: 60 })
|
||||
return true
|
||||
} catch {}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
let browser
|
||||
let abortBrowser
|
||||
@ -167,71 +146,64 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
})
|
||||
|
||||
console.log('[bloomberg] navigating to login page')
|
||||
await page.goto('https://www.bloomberg.com/account/signin', {
|
||||
const loginResponse = await page.goto('https://www.bloomberg.com/account/signin', {
|
||||
waitUntil: 'networkidle2',
|
||||
timeout: 60000,
|
||||
})
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
|
||||
const pageInputs = await page.evaluate(() =>
|
||||
Array.from(document.querySelectorAll('input')).map(i => ({
|
||||
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
|
||||
}))
|
||||
)
|
||||
console.log('[bloomberg] login input count:', pageInputs.length)
|
||||
|
||||
|
||||
const emailOk = await tryType(page, [
|
||||
const failLogin = reason => {
|
||||
console.log('[bloomberg] login outcome:', reason)
|
||||
throw new Error('authentication unavailable')
|
||||
}
|
||||
if (!loginResponse) failLogin('login_navigation_unavailable')
|
||||
if (loginResponse.status() !== 200) failLogin([401,403].includes(loginResponse.status()) ? 'access_denied' : 'login_http_unavailable')
|
||||
const rejectBlocked = async () => {
|
||||
const reason = classifyLoginState(await page.evaluate(inspectLoginState))
|
||||
if (['challenge','two_factor_required','auth_rejected'].includes(reason)) failLogin(reason)
|
||||
}
|
||||
await rejectBlocked()
|
||||
if (!trustedLoginOrigin(page.url())) failLogin('login_origin_unavailable')
|
||||
const emailOk = await typeVisibleInput(page, [
|
||||
'#email-form-input',
|
||||
'input[id="email-form-input"]',
|
||||
'input[type="email"]',
|
||||
'input[name="text-input"]',
|
||||
'input[placeholder*="email" i]',
|
||||
], username)
|
||||
if (!emailOk) throw new Error('could not find email input')
|
||||
if (!emailOk) failLogin('email_form_unavailable')
|
||||
|
||||
await new Promise(r => setTimeout(r, 800))
|
||||
|
||||
const submitted = await page.evaluate(() => {
|
||||
const btn = Array.from(document.querySelectorAll('button')).find(b =>
|
||||
b.type === 'submit' || /continue|next|sign.?in/i.test(b.textContent)
|
||||
)
|
||||
if (btn) { btn.click(); return true }
|
||||
const form = document.querySelector('form')
|
||||
if (form) { form.submit(); return true }
|
||||
return false
|
||||
})
|
||||
if (!submitted) await page.keyboard.press('Enter')
|
||||
const submitted = await page.evaluate(submitInputForm, emailOk)
|
||||
if (!submitted) failLogin('login_form_unavailable')
|
||||
|
||||
try {
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('input[type="password"]') !== null,
|
||||
{ timeout: 10000 }
|
||||
)
|
||||
await page.waitForSelector('input[type="password"]', { visible:true, timeout:10000 })
|
||||
} catch {
|
||||
await new Promise(r => setTimeout(r, 3000))
|
||||
}
|
||||
await rejectBlocked()
|
||||
if (!trustedLoginOrigin(page.url())) failLogin('login_origin_unavailable')
|
||||
console.log('[bloomberg] email step completed')
|
||||
|
||||
const pwdOk = await tryType(page, [
|
||||
const pwdOk = await typeVisibleInput(page, [
|
||||
'input[type="password"]',
|
||||
'input[name="password"]',
|
||||
'input[autocomplete="current-password"]',
|
||||
'input[autocomplete="password"]',
|
||||
], password)
|
||||
if (!pwdOk) throw new Error('could not find password input')
|
||||
if (!pwdOk) failLogin('password_form_unavailable')
|
||||
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
await Promise.all([
|
||||
page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {}),
|
||||
tryClick(page, ['button[type="submit"]', 'input[type="submit"]']),
|
||||
])
|
||||
|
||||
const currentURL = page.url()
|
||||
console.log('[bloomberg] login navigation completed')
|
||||
if (currentURL.includes('/account/signin')) {
|
||||
throw new Error('login did not redirect')
|
||||
}
|
||||
if (!await page.evaluate(submitInputForm, pwdOk)) failLogin('login_form_unavailable')
|
||||
// SPA login may complete without navigation; leaving sign-in alone is
|
||||
// never evidence of authentication. Wait for explicit terminal DOM state.
|
||||
await page.waitForFunction(inspectLoginState, { timeout:10000 }, true).catch(() => {})
|
||||
const outcome = classifyLoginState(await page.evaluate(inspectLoginState))
|
||||
if (outcome !== 'authenticated') failLogin(outcome)
|
||||
if (!authenticatedDestination(page.url())) failLogin('authentication_unconfirmed')
|
||||
console.log('[bloomberg] login outcome: authenticated')
|
||||
|
||||
return page
|
||||
}
|
||||
@ -240,6 +212,7 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
const page = enrichment
|
||||
? await Promise.race([login(), new Promise((resolve, reject) => {
|
||||
loginTimer = setTimeout(() => {
|
||||
console.log('[bloomberg] login outcome: login_timeout')
|
||||
abortBrowser?.()
|
||||
reject(new Error('enrichment login expired'))
|
||||
}, 30000)
|
||||
|
||||
Reference in New Issue
Block a user