【问题标题】:Parsing HTML code in R在 R 中解析 HTML 代码
【发布时间】:2016-02-29 15:18:31
【问题描述】:

我目前正在尝试在 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 的特定部分

&lt;h4 class="dataHeaderWithBorder"&gt;Writing Credits

结尾

&lt;h4 name="cast" id="cast" class="dataHeaderWithBorder"&gt;

任何帮助将不胜感激。

【问题讨论】:

  • 您可能应该阅读this“机器人和屏幕抓取:您不得在本网站上使用数据挖掘、机器人、屏幕抓取或类似的数据收集和提取工具,除非使用我们明确的书面同意如下所述。omdbapiR 包可能有你需要的东西而不是违反 ToS。
  • 哦,是的,哎呀,对不起。我可以使用 IMDB 提供的 .list 文件。
  • 如果您在另一个允许这样做的站点上遇到类似问题,rvest 可能是您尝试做的更好的包。见哈德利的tutorial
  • 确实,我目前正在使用 rvest 解决另一个问题,但是我遇到了报废问题。当我抓取信息时,它会生成一个包含 3 行的向量。我需要将此具有 3 行的向量转换为 1 单行。一直在看粘贴之类的功能,还没有喜出望外。

标签: xml r rcurl


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2015-10-09
    • 2011-04-07
    相关资源
    最近更新 更多