我想在 R 中读取 URL 的内容(例如,http://www.haaretz.com/)。我想知道我该怎么做
最佳答案
不太确定您要如何处理该页面,因为它真的很乱。正如我们re-learned in this famous stackoverflow question , 在 html 上做正则表达式不是一个好主意,所以你肯定会想用 XML 包来解析它。
这是一个让您入门的示例:
require(RCurl)
require(XML)
webpage <- getURL("http://www.haaretz.com/")
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)
# parse the tree by tables
x <- xpathSApply(pagetree, "//*/table", xmlValue)
# do some clean up with regular expressions
x <- unlist(strsplit(x, "\n"))
x <- gsub("\t","",x)
x <- sub("^[[:space:]]*(.*?)[[:space:]]*$", "\\1", x, perl=TRUE)
x <- x[!(x %in% c("", "|"))]
这会产生一个主要由网页文本(以及一些 javascript)组成的字符向量:
> head(x)
[1] "Subscribe to Print Edition" "Fri., December 04, 2009 Kislev 17, 5770" "Israel Time:Â 16:48Â (EST+7)"
[4] "Â Â Make Haaretz your homepage" "/*check the search form*/" "function chkSearch()"
关于html - 如何读取和解析 R 中网页的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1844829/