Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for baseUrl config item #44

Merged
merged 4 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions buildQueryString.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@
const buildQueryString = (query) => {
// Sanity check
if (
!query ||
typeof query !== 'object' ||
!query ||
typeof query !== 'object' ||
Object.keys(query).length === 0
) {
return ''
}
// Build and return query string
return Object.keys(query).map(key => `${key}=${query[key]}`).join('&')
// Build query string
// Example: { q: 'puppies', hl: 'en', gl: 'US' } => '?q=puppies&hl=en&gl=US'
const queryString = Object.keys(query).reduce((acc, key, index) => {
const prefix = index === 0 ? '?' : '&'
return `${acc}${prefix}${key}=${query[key]}`
}, '')

return queryString
}

module.exports = {
Expand Down
34 changes: 21 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,23 @@ const getArticleContent = require('./getArticleContent').default;
const googleNewsScraper = async (userConfig) => {

const config = Object.assign({
prettyURLs: true,
getArticleContent: false,
timeframe: "7d",
puppeteerArgs: [],
prettyURLs: true,
getArticleContent: false,
puppeteerArgs: [],
}, userConfig);

const queryString = config.queryVars ? buildQueryString(config.queryVars) : ''
const url = `https://news.google.com/search?${queryString}&q=${config.searchTerm} when:${config.timeframe || '7d'}`
console.log(`📰 SCRAPING NEWS FROM: ${url}`);

let queryVars = config.queryVars || {};
if (config.searchTerm) {
queryVars.q = config.query;
}

const queryString = config.queryVars ? buildQueryString(queryVars) : ''
const baseUrl = config.baseUrl ?? `https://news.google.com/search`
const timeString = config.timeframe ? ` when:${config.timeframe}` : ''
const url = `${baseUrl}${queryString}${timeString}`

console.log(`📰 SCRAPING NEWS FROM: ${url}`);
const requiredArgs = [
'--disable-extensions-except=/path/to/manifest/folder/',
'--load-extension=/path/to/manifest/folder/',
Expand Down Expand Up @@ -46,16 +54,16 @@ const googleNewsScraper = async (userConfig) => {
})
await page.setCookie({
name: "CONSENT",
value: `YES+cb.${new Date().toISOString().split('T')[0].replace(/-/g,'')}-04-p0.en-GB+FX+667`,
value: `YES+cb.${new Date().toISOString().split('T')[0].replace(/-/g, '')}-04-p0.en-GB+FX+667`,
domain: ".google.com"
});
await page.goto(url, { waitUntil: 'networkidle2' });

try {
await page.$(`[aria-label="Reject all"]`);
await Promise.all([
page.click(`[aria-label="Reject all"]`),
page.waitForNavigation({waitUntil: 'networkidle2'})
page.click(`[aria-label="Reject all"]`),
page.waitForNavigation({ waitUntil: 'networkidle2' })
]);
} catch (err) {
// console.log("ERROR REJECTING COOKIES:", err);
Expand All @@ -69,12 +77,12 @@ const googleNewsScraper = async (userConfig) => {
let i = 0
const urlChecklist = []

$(articles).each(function() {
$(articles).each(function () {
const link = $(this).find('a[href^="./article"]').attr('href').replace('./', 'https://news.google.com/') || false
link && urlChecklist.push(link);
const srcset = $(this).find('figure').find('img').attr('srcset')?.split(' ');
const image = srcset && srcset.length
? srcset[srcset.length-2]
const image = srcset && srcset.length
? srcset[srcset.length - 2]
: $(this).find('figure').find('img').attr('src');
const mainArticle = {
"title": $(this).find('h4').text() || $(this).find('div > div + div > div a').text(),
Expand Down