Created
April 3, 2019 16:35
-
-
Save diyclassics/c97ccc673b3ecfef2a2a644fcc7f86d2 to your computer and use it in GitHub Desktop.
Get Perseus Short Defs in Google Sheets
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
function getShortDef(input) { | |
var array = []; | |
var url = "http://www.perseus.tufts.edu/hopper/morph?l=" + input; | |
var page = UrlFetchApp.fetch(url); | |
var doc = Xml.parse(page, true); | |
var bodyHtml = doc.html.body.toXmlString(); | |
doc = XmlService.parse(bodyHtml); | |
var root = doc.getRootElement(); | |
var entries = getElementsByClassName(root, 'lemma_definition'); | |
for (var i = 0; i < entries.length; i++) { | |
array.push(entries[i].getText().trim()); | |
} | |
return array.join('; '); | |
} | |
// https://sites.google.com/site/scriptsexamples/learn-by-example/parsing-html | |
function getElementsByClassName(element, classToFind) { | |
var data = []; | |
var descendants = element.getDescendants(); | |
descendants.push(element); | |
for(i in descendants) { | |
var elt = descendants[i].asElement(); | |
if(elt != null) { | |
var classes = elt.getAttribute('class'); | |
if(classes != null) { | |
classes = classes.getValue(); | |
if(classes == classToFind) data.push(elt); | |
else { | |
classes = classes.split(' '); | |
for(j in classes) { | |
if(classes[j] == classToFind) { | |
data.push(elt); | |
break; | |
} | |
} | |
} | |
} | |
} | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment