【问题标题】:Parsing HTML elements by id and class with XML package使用 XML 包通过 id 和 class 解析 HTML 元素
【发布时间】:2015-03-04 03:12:17
【问题描述】:

是否可以通过idclass 信息从HTMLInternalDocument 对象中提取元素?例如让我们拿一个文件:

<!DOCTYPE html>
<html>
<head>
    <title>R XML test</title>
</head>
<body>
<div id="obj1">
    <p id="txt1">quidquid</p>
    <p id="txt2">Latine dictum</p>
</div>
<div class="mystuff">
    <p>sit altum</p>
    <p>videtur</p>
</div>
</body>
</html>

读入R如下:

require(XML)
file <- "C:/filepath/index.html"
datain <- htmlTreeParse(readLines(file), useInternalNodes = TRUE)

我想提取元素id='txt2'class='mystuff'的内容。

我尝试了各种方法都没有成功,它们似乎都在迭代树,这非常费力。是否有使用 class/id 的快捷方法?我有一个想法,它可能涉及首先使用getNodeSet,然后是一些应用方法(例如xmlApplyxmlAttrs),但我没有尝试过任何工作。感谢任何指点。

【问题讨论】:

  • 你的“内容”是什么意思,文本?试试cat(sapply(datain['//*[@id = "txt2"] | //*[@class = "mystuff"]'], xmlValue))
  • 这看起来很有希望。原谅我的无知,之前没见过这个公式datain['//*[@id = "txt2"]']是不是XML库方法?
  • 详情请看?getNodeSet下的帮助:getNodeSet(datain, '//*[@id = "txt2"]')

标签: r html-parsing


【解决方案1】:

试试这个例子:

id_or_class_xp <- "//p[@id='txt2']//text() | //div[@class='mystuff']//text()"
xpathSApply( doc,id_or_class_xp,xmlValue)

[1] "Latine dictum" "\n    "        "sit altum"     "\n    "        "videtur"       "\n" 

文档在哪里:

doc <- htmlParse('<!DOCTYPE html>
<html>
<head>
    <title>R XML test</title>
</head>
<body>
<div id="obj1">
    <p id="txt1">quidquid</p>
    <p id="txt2">Latine dictum</p>
</div>
<div class="mystuff">
    <p>sit altum</p>
    <p>videtur</p>
</div>
</body>
</html>',asText=T)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多