當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。