【问题标题】:Reading data from an html table input tag in R从R中的html表输入标签读取数据
【发布时间】:2021-06-07 20:24:43
【问题描述】:

我正在尝试将 HTML 表格从内部网页读入 R。

不幸的是,<td> 的结构很奇怪,所以我不能使用 rvest 包中的 html_table() 为我执行此操作。

html表的结构如下:

<table>
   <tr>
      <td>
         <input disabled name="Attribute A" value="15.00">
      </td>
   </tr>
</table>

然后每行重复多个&lt;td&gt;。我想提取每个条目的值,我只是有点不确定如何。

我一直在考虑编写一个解析器,将每个&lt;td&gt; 的内容扔到相应的列中,然后使用正则表达式匹配name="Attribute A" 并返回值。但是,这似乎很复杂,我希望有一个更有效的选择:)

【问题讨论】:

    标签: r rvest


    【解决方案1】:

    也许这有助于开始:

    your_url <- read_html(url)
    html_nodes(your_url, xpath = '//input') %>% html_attr('name')
    

    或更笼统地说:

    your_url <- read_html(url)
    
    #option 1
    html_nodes(your_url, xpath = '//td') %>%
      html_text() 
        
    #option 2
    html_nodes(your_url, xpath = '//table//tr') %>%
      html_text() 
    

    【讨论】:

    • 不幸的是,这不起作用。 'html_text()' 没有返回标签内的文本。我最终做的是:''' file.Read % html_nodes(xpath = '//input') %>% html_attrs()
    【解决方案2】:

    我最终做的是:

    vars = c("name", "value") #Define attributes you want to keep
    
    file.Read <- read_html(file)
    
    file.Read %>% 
       html_nodes(xpath = '//input') %>%
       html_attrs() %>%
       lapply(function(x) {unlist(x[vars])})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2020-08-13
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多