【问题标题】:Save `xml_document/xml_node` object in a tibble for mutating将 `xml_document/xml_node` 对象保存在 tibble 中以进行变异
【发布时间】:2021-11-02 19:51:07
【问题描述】:

我想将一个 html 页面保存到一个 tibble 中,以便以后可以在页面内容上使用 mutate

我想过把html直接读到一个tibble:

library(tidyverse)
library(rvest)

#does not work
tibble(html=read_html("https://www.accessdata.fda.gov/scripts/cder/daf/index.cfm?event=overview.process&ApplNo=040445"))
#> Error: All columns in a tibble must be vectors.
#> x Column `html` is a `xml_document/xml_node` object.

list 的身份阅读作品:

#works
works <- tibble(html=list(read_html("https://www.accessdata.fda.gov/scripts/cder/daf/index.cfm?event=overview.process&ApplNo=040445")))
works
#> # A tibble: 1 x 1
#>   html      
#>   <list>    
#> 1 <xml_dcmn>

但是,我不能使用 mutate 然后:

# does not work
works %>% 
  mutate(table=html_nodes(unlist(page),"#exampleApplSuppl"))
#> Error: Problem with `mutate()` column `table`.
#> i `table = html_nodes(unlist(page), "#examleApplSuppl")`.

reprex package (v2.0.1) 于 2021-11-02 创建

【问题讨论】:

  • 如果有人使用这种方法并想要存储结果。从 .rds 文件重新加载此 tibble 后,html_nodes 会给您错误:external pointer is not valid。这是因为外部指针只存储在内存中。见解决方案here

标签: r web-scraping tidyverse


【解决方案1】:

由于 'html' 列是 list,循环遍历 list 并在 list 中返回输出

library(purrr)
library(dplyr)
works %>% 
   mutate(table = map(html, ~ html_nodes(.x, "#examleApplSuppl")))

-输出

# A tibble: 1 × 2
  html       table     
  <list>     <list>    
1 <xml_dcmn> <xml_ndst>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-30
    • 2017-04-08
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多