当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R rvest html_attr 获取元素属性


html_attr() 获取单个属性; html_attrs() 获取所有属性。

用法

html_attr(x, name, default = NA_character_)

html_attrs(x)

参数

x

文档(来自 read_html() )、节点集(来自 html_elements() )、节点(来自 html_element() )或会话(来自 session() )。

name

要检索的属性的名称。

default

当该属性不存在于每个元素中时用作默认值的字符串。

x 长度相同的字符向量(对于 html_attr() )或列表 ( html_attrs() )。

例子

html <- minimal_html('<ul>
  <li><a href="https://a.com" class="important">a</a></li>
  <li class="active"><a href="https://c.com">b</a></li>
  <li><a href="https://c.com">b</a></li>
  </ul>')

html %>% html_elements("a") %>% html_attrs()
#> [[1]]
#>            href           class 
#> "https://a.com"     "important" 
#> 
#> [[2]]
#>            href 
#> "https://c.com" 
#> 
#> [[3]]
#>            href 
#> "https://c.com" 
#> 

html %>% html_elements("a") %>% html_attr("href")
#> [1] "https://a.com" "https://c.com" "https://c.com"
html %>% html_elements("li") %>% html_attr("class")
#> [1] NA       "active" NA      
html %>% html_elements("li") %>% html_attr("class", default = "inactive")
#> [1] "inactive" "active"   "inactive"
源代码:R/html.R

相关用法


注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Get element attributes。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。