【问题标题】:rvest how to select a specific css node by idrvest 如何通过 id 选择特定的 css 节点
【发布时间】:2015-11-14 16:00:05
【问题描述】:

我正在尝试使用 rvest 包从网页中抓取数据。在一个简单的格式中,html 代码如下所示:

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

我想从第一个输入中获取值 123。我尝试了以下 R 代码:

library(rvest)
url<-"xxx"
output<-html_nodes(url, ".style input")

这将返回一个输入标签列表:

[[1]]
<input id="a" value="123">
[[2]]
<input id="b">

接下来我尝试使用 html_node 通过 id 引用第一个输入标记:

html_node(output, "#a")

这里它返回了一个空值列表,而不是我想要的输入标签。

[[1]]
NULL
[[2]]
NULL

我的问题是,如何使用其 id 引用输入标签?

【问题讨论】:

    标签: html css r web-scraping rvest


    【解决方案1】:

    你可以使用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")
    

    获取 css- 和 xpath-selector 的最简单方法是使用 http://selectorgadget.com/。 对于像您这样的特定属性,请使用 chrome 的开发人员工具栏获取 xpath,如下所示:

    【讨论】:

      【解决方案2】:

      这将适用于直接的 CSS 选择器:

      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"
      

      【讨论】:

        【解决方案3】:

        添加答案 bc 我没有看到用于按 id 选择的简单 css 选择器简写:使用 #your_id_name:

        h %>% 
          html_node('#a') %>%
          html_attr('value')
        

        根据需要输出“123”。

        与其他设置相同:

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

        【讨论】:

          猜你喜欢
          • 2020-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多