Created
April 3, 2013 07:22
-
-
Save juba/5299095 to your computer and use it in GitHub Desktop.
Function to get a code block from a StackOverflow question.
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
##' 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