Last active
August 31, 2022 10:56
-
-
Save Ivannnnn/ed14223ccd7fc573f512657dbbdaa445 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = (...args) => | |
import("node-fetch").then(({ default: fetch }) => fetch(...args)); | |
const { buildQueryStr, timeTaken } = require("./helpers.js"); | |
async function getSource({ q, ...params } = {}, page = 1) { | |
if (!q) throw Error("{ q } is a manadatory parameter!"); | |
const url = | |
`https://www.google.com/search?` + | |
buildQueryStr({ | |
pws: 0, | |
adtest: "off", | |
lr: "lang_en", | |
hl: "en", | |
q, | |
start: (page - 1) * 10, | |
...params, | |
}); | |
return await fetch(url).then((r) => r.text()); | |
} | |
function parseSource(htmlStr) { | |
const urls = [ | |
...htmlStr.matchAll(/class="egMi0 kCrYT"><a href="\/url\?q=(.+?)&/g), | |
].map((match) => match[1]); | |
const titles = [ | |
...htmlStr.matchAll(/class="BNeawe vvjwJb AP7Wnd">(.+?)</g), | |
].map((match) => match[1]); | |
return urls.map((url, i) => ({ url, title: titles[i] })); | |
} | |
async function get(params, page) { | |
return parseSource(await getSource(params, page)); | |
} | |
module.exports = { getSource, parseSource, get }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment