Skip to content

Instantly share code, notes, and snippets.

@juba
Created April 3, 2013 07:22
Show Gist options
  • Save juba/5299095 to your computer and use it in GitHub Desktop.
Save juba/5299095 to your computer and use it in GitHub Desktop.
Function to get a code block from a StackOverflow question.
##' Get code block from a SO question
##'
##' @param id question id
##' @param index index of the code block to return (one number only)
##' @param cat.output cat the content of the code blocks
##' @import XML
##' @export
get.so <- function (id, index=NULL, cat.output=FALSE) {
doc <- htmlParse(paste("http://stackoverflow.com/questions/",id,sep=""))
pre.index <- ifelse(is.null(index), "", paste("[",as.character(index),"]",sep=""))
xpath <- paste("//div[@id=\"question\"]//div[@class=\"post-text\"]//pre",pre.index,"/code",sep="")
code <- getNodeSet(doc, xpath)
code <- lapply(code, getChildrenStrings)
if (cat.output) return(invisible(lapply(code, cat)))
if (length(code)==1) return(unlist(code))
code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment