gpt4 book ai didi

html - 如何读取和解析 R 中网页的内容

转载 作者:技术小花猫 更新时间:2023-10-29 12:36:00 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com