Created
October 28, 2019 19:47
-
-
Save dsottimano/2c8428b0bac422b3bcf08744c73b2be0 to your computer and use it in GitHub Desktop.
SERPapi for Google sheets/apps script
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
//note: users of this script need a valid api key from serpapi.com | |
//the key must be included in the object below as the serpApiKey value. For non-programmers, please ensure that your API is within quotes ("") | |
var GLOBAL_VARIABLES = { | |
serpApiKey: "" | |
} | |
/** | |
* Returns serpapi data for organic results | |
* | |
* @param {"cars"} query REQUIRED The search term you want to query for | |
* @param {"en"} language OPTIONAL The language you want to search in. Default is "en" for English | |
* @param {"us"} country OPTIONAL The country you want to search in. Default is "us" for United States | |
* @param {10} num OPTIONAL The number of results you want to return. Acceptable values are 10, 20, 50, 100. Default is 10 | |
* @param {"desktop"} device OPTIONAL The device you want results for. Acceptable values are "mobile", "tablet" or "desktop" Default is desktop | |
* @return number | |
* @customfunction | |
*/ | |
function GOOGLE_SEARCH(query,language,country,num,device) { | |
if(Array.isArray(query) || query == "") return "Please enter a single query string" | |
try { | |
var location = (location || "585069adee19ad271e9b7e61"), | |
language = language || "en", | |
country = country || "us", | |
device = (device || "desktop"), | |
num = num || 10, | |
res, | |
url, | |
resultArray = [] | |
url = "https://serpapi.com/search?q="+query+"&hl="+language+"&gl="+country+"&device="+device+"&api_key="+GLOBAL_VARIABLES.serpApiKey+"&num="+num | |
request = UrlFetchApp.fetch(url, {muteHttpExceptions:true}).getContentText() | |
res = JSON.parse(request) | |
if(res.error) throw res.error | |
if (!res["organic_results"]) return ["No results found"] | |
res["organic_results"].forEach(function(item) { | |
resultArray.push(item.link) | |
}) | |
if (resultArray.length > 0) return resultArray | |
return "No results found"; | |
} | |
catch(e) { | |
return e | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment