【问题标题】:How can I read and parse the contents of a webpage in R如何在 R 中读取和解析网页的内容
【发布时间】:2010-12-23 02:57:16
【问题描述】:

我想在 R 中阅读 URL 的内容(例如,http://www.haaretz.com/)。我想知道我该怎么做

【问题讨论】:

    标签: html r screen-scraping html-content-extraction


    【解决方案1】:

    不确定你想如何处理那个页面,因为它真的很乱。正如我们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()" 
    

    【讨论】:

    • OOOhhhhh 哇......我正在废弃一个动态网站,我在过去 7-8 小时内完成了所有工作,但无法做到 - 这个对我有用。救命恩人
    【解决方案2】:

    您最好的选择可能是 XML 包 - 例如,请参见 previous question

    【讨论】:

    • 但是如何正确地摆脱 html 标签。我知道我可以写一个 RegEx 表达式,但是有没有任何包可以使编码不那么引人注目!
    【解决方案3】:

    我知道你要求 R。但也许 python+beautifullsoup 是这里的前进方向?然后用 R 做分析你用beautifullsoup 刮屏了吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2012-08-19
      • 1970-01-01
      • 2017-03-24
      相关资源
      最近更新 更多