JMichaelTX
5/30/2015 - 2:24 AM

Harvest Google result links from Safari with XPATH (as MD) with //*[@class='r']/a

Harvest Google result links from Safari with XPATH (as MD) with //*[@class='r']/a

// YOSEMITE Javascript for Applications JXA
// Capture the main result links from a Google search page as Markdown
// ( Using XPath to search for <a> elements which are children
// of elements with class 'r'

var resultLinksMD = function () {
	var r = document.evaluate(
			"//*[@class='r']/a",
			document, null, 0, null
		),
		lst = [], a;

	while (a = r.iterateNext()) {
		lst.push("[" + a.text + "](" + a.href + ")");
	}
	return lst.join("\n");
};

function run() {
	var app = Application.currentApplication(),
		appSafari = Application("Safari"),
		lstDocs = appSafari.documents(),
		oDoc = lstDocs.length ? lstDocs[0] : null,
		strJS = "(" + resultLinksMD.toString() + ")()";
		
	var strResult= (oDoc && (oDoc.name().indexOf("Google Search") !== -1)) ?
		appSafari.doJavaScript(strJS, { in: appSafari.windows[0].currentTab }):
		"Not a Google Search page:\n" + oDoc.url();

	app.includeStandardAdditions = true;
	app.setTheClipboardTo(strResult);
	
	return strResult;
}