rvest how to select a specific css node by id

别说谁变了你拦得住时间么 提交于 2019-12-03 06:26:29
Rentrop

You can use xpath:

require(rvest)
text <- '<div class="style">
   <input id="a" value="123">
   <input id="b">
</div>'

h <- read_html(text)

h %>% 
  html_nodes(xpath = '//*[@id="a"]') %>%
  xml_attr("value")

The easiest way to get css- and xpath-selector is to use http://selectorgadget.com/. For a specific attribute like yours use chrome's developer toolbar to get the xpath as follows:

This will work just fine with straight CSS selectors:

library(rvest)

doc <- '<div class="style">
   <input id="a" value="123">
   <input id="b">
</div>'

pg <- html(doc)
html_attr(html_nodes(pg, "div > input:first-of-type"), "value")

## [1] "123"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!