Created
November 8, 2017 21:14
-
-
Save vmandic/99d511650b41cab459f6d2e27a1e09fa to your computer and use it in GitHub Desktop.
A short snippet providing two functions to process a Google search query from the console while on www.google.* website.
This file contains hidden or 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
| function searchGoogleForString(searchStr) { | |
| var baseLink = "https://" + window.location.hostname + "/search?q=" + searchStr; | |
| var xhr = new XMLHttpRequest(); | |
| xhr.open("GET", baseLink, true); | |
| xhr.onload = function () { | |
| if (xhr.readyState === 4 && xhr.status === 200) { | |
| var d = document.createElement("div"); | |
| d.innerHTML = xhr.response; | |
| var resNodes = d.querySelectorAll("div#resultStats"); | |
| if (!resNodes || resNodes.length !== 1) { | |
| throw "resNodes is invalid, perhaps Google changed their HTML..."; | |
| } | |
| var resultStats = resNodes[0]; | |
| var text = resultStats.childNodes[0].wholeText; | |
| var searchCount = Number(text.split(" ")[1].replace(/\./g, "")); | |
| console.log("Count for '" + searchStr + "': " + searchCount); | |
| } else { | |
| throw "Web request to Google failed..."; | |
| } | |
| }; | |
| xhr.send(null); | |
| } | |
| function searchGoogleForStrings() { | |
| if (arguments.length < 1) { | |
| throw "Could not search as no words were provided. Enter comma delimited strings to search Google."; | |
| } | |
| console.log("Querying..."); | |
| var searchWords = arguments; | |
| for (var i = 1; i <= searchWords.length; i++) { | |
| // capture variable i to local scope... | |
| var sec = i; | |
| var sw = searchWords[sec-1]; | |
| if (typeof sw !== "string"){ | |
| console.warn("Skipping parameter #" + sec + " as it is not type of string."); | |
| continue; | |
| } | |
| // min delay of 500ms | |
| var timeout = Math.round(((Math.random() * 2000 * sec) + (500))); | |
| setTimeout(searchGoogleFor.bind(this, sw, sec == searchWords.length), timeout); | |
| if (sec == searchWords.length) { | |
| setTimeout(function(){ console.log("Processing last query..."); }, timeout + 1); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment