如何在 R 中使用 html_nodes 到 select 节点和 "attribute = x"?

How do I use html_nodes to select nodes with "attribute = x" in R?

我有一组 html 页。我想提取属性 "border" = 1 的所有 table 节点。这是一个示例:

<table border="1" cellspacing="0" cellpadding="5">
   <tbody><tr><td>
    <table border="0" cellpadding="2" cellspacing="0">
      <tbody><tr>
        <td bgcolor="#ff9999"><strong><font size="+1">CASEID</font></strong></td>
      </tr></tbody>
    </table>
   <tr><td>[tbody]
</table>

在示例中,我想要 select 边界 = 1 的 table 节点,而不是边界 = 0 的 table 节点。我正在使用 html_nodes()来自 rvest 但不知道如何添加属性:

html_nodes(x, "table")

查看从 html_nodes 的文档链接的 CSS3 selectors documentation。它提供了 CSS select 或语法的详尽解释。

对于你的情况,你想要

html_nodes(x, "tag[attribute]")

到 select 所有 tag 设置了 attribute,或

html_nodes(x, "tag[attribute=value]")

到 select 所有 tagattribute 设置为 value

从 HTML 和类似文档中查找节点的主要方法有两种:CSS 选择器和 XPath。 CSS 通常更容易,但不能用于更复杂的用例,而 XPath 具有可以执行诸如在节点内搜索文本之类的功能。使用哪一个是always up for debate,但我认为两者都值得尝试。

library(rvest)

with_css <- html_nodes(x, css = "table[border='1']")
with_css
#> {xml_nodeset (1)}
#> [1] <table border="1" cellspacing="0" cellpadding="5"><tbody>\n<tr><td>\n     ...

验证 table 看起来正确:

html_table(with_css, fill = TRUE)
#> [[1]]
#>        X1     X2
#> 1  CASEID CASEID
#> 2  CASEID   <NA>
#> 3 [tbody]   <NA>

等效的 XPath 得到相同的 table。

with_xpath <- html_nodes(x, xpath = "//table[@border=1]")
with_xpath
#> {xml_nodeset (1)}
#> [1] <table border="1" cellspacing="0" cellpadding="5"><tbody>\n<tr><td>\n     ...
html_table(with_xpath, fill = TRUE)
#> [[1]]
#>        X1     X2
#> 1  CASEID CASEID
#> 2  CASEID   <NA>
#> 3 [tbody]   <NA>