首页 > 解决方案 > 假设它们具有不同的长度,如何将标题作为与 rvest 的段落不同的列?

问题描述

我想抓取以下网址:“https://www.constituteproject.org/constitution/Cuba_2018D?lang=es”

这是一个宪法,在 CSS 选择器“.float-left”处为文档的每个部分都有一个标题,在“p”中为每个部分的内容。我想使用列中的每个部分来识别每个段落。但是,这两个部分的长度不同。

到目前为止,我已经尝试了以下方法:

pacman::p_load(tidyverse, rvest)


url <- "https://www.constituteproject.org/constitutions?lang=es"
content <-  tryCatch(
  url %>%
    as.character() %>% 
    read_html() %>% 
    html_nodes('p') %>% 
    html_text())


titulo <-  tryCatch(
  url %>%
    as.character() %>% 
    read_html() %>% 
    html_nodes('.float-left') %>% 
    html_text())


final <- bind_cols(titulo, content)

标签: rrvest

解决方案


实现所需结果的一种选择是使用例如将标题和内容提取为数据框map_dfr。为此,我首先通过 CSS 选择器提取包含标题和内容的节点section .article-list .level2。为了处理不同的长度,您可以将可能包含多个段落的内容放在列表列中,以后可以取消嵌套。此外,为了只保留ARTICULOS我必须添加一个filter来过滤掉也通过 CSS 选择器提取的部分。

library(rvest)
library(tidyverse)

url <- "https://www.constituteproject.org/constitution/Cuba_2018D?lang=es"

html <- read_html(url)

foo <- html %>% 
  html_nodes('section .article-list .level2') 

final <- map_dfr(foo, ~ tibble(
  titulo = html_nodes(.x, '.float-left') %>% html_text(),
  content = list(html_nodes(.x, "p") %>% html_text()))) %>% 
  filter(!grepl("^SEC", titulo)) %>% 
  unnest_longer(content)

final
#> # A tibble: 2,145 × 2
#>    titulo     content                                                           
#>    <chr>      <chr>                                                             
#>  1 ARTÍCULO 1 Cuba es un Estado socialista de derecho, democrático, independien…
#>  2 ARTÍCULO 2 El nombre del Estado cubano es República de Cuba, el idioma ofici…
#>  3 ARTÍCULO 3 La defensa de la patria socialista es el más grande honor y el de…
#>  4 ARTÍCULO 3 El socialismo y el sistema político y social revolucionario, esta…
#>  5 ARTÍCULO 3 Los ciudadanos tienen el derecho de combatir por todos los medios…
#>  6 ARTÍCULO 4 Los símbolos nacionales son la bandera de la estrella solitaria, …
#>  7 ARTÍCULO 4 La ley define los atributos que los identifican, sus característi…
#>  8 ARTÍCULO 5 El Partido Comunista de Cuba, único, martiano, fidelista y marxis…
#>  9 ARTÍCULO 6 La Unión de Jóvenes Comunistas, organización de  la juventud cuba…
#> 10 ARTÍCULO 7 La Constitución es la norma suprema del Estado. Todos están oblig…
#> # … with 2,135 more rows

推荐阅读