Skip to content

Instantly share code, notes, and snippets.

@dsottimano
Created October 28, 2019 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dsottimano/2c8428b0bac422b3bcf08744c73b2be0 to your computer and use it in GitHub Desktop.
Save dsottimano/2c8428b0bac422b3bcf08744c73b2be0 to your computer and use it in GitHub Desktop.
SERPapi for Google sheets/apps script
//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