【发布时间】:2010-12-23 02:57:16
【问题描述】:
我想在 R 中阅读 URL 的内容(例如,http://www.haaretz.com/)。我想知道我该怎么做
【问题讨论】:
标签: html r screen-scraping html-content-extraction
我想在 R 中阅读 URL 的内容(例如,http://www.haaretz.com/)。我想知道我该怎么做
【问题讨论】:
标签: html r screen-scraping html-content-extraction
不确定你想如何处理那个页面,因为它真的很乱。正如我们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()"
【讨论】:
您最好的选择可能是 XML 包 - 例如,请参见 previous question。
【讨论】:
我知道你要求 R。但也许 python+beautifullsoup 是这里的前进方向?然后用 R 做分析你用beautifullsoup 刮屏了吗?
【讨论】: