我目前正在尝试解析R中的HTML代码。目前我正在使用XML和RCurl包来解析信息。
webpage <- getURL("http://www.imdb.com/title/tt0809504/fullcredits?ref_=tt_ov_wr#writers")
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)
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("", "|"))]
head(x)
但是,我真正想做的只是解析以
开头的html的特定部分 <h4 class="dataHeaderWithBorder">Writing Credits
以
结尾 <h4 name="cast" id="cast" class="dataHeaderWithBorder">
任何帮助都会受到极大的赞赏。
答案 0 :(得分:1)
这个问题并未准确指出所需的输出,但这是一个自包含的示例,它返回指示的节点。
library(XML)
Lines <- '<a>
<b class = "Z">abc - ABC</b>
<b class = "Z">xyz - XYZ</b>
<b>def - DEF</b>
</a>'
doc <- htmlTreeParse(Lines, asText = TRUE)
xpath <- "//b[@class = 'Z' and contains(., 'xyz')]"
getNodeSet(xmlRoot(doc), xpath)
,并提供:
[[1]]
<b class="Z">xyz - XYZ</b>