r - 假设它们具有不同的长度,如何将标题作为与 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)
解决方案
实现所需结果的一种选择是使用例如将标题和内容提取为数据框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
推荐阅读
- windows - 在不重新编译的情况下强制在高端内存中加载进程的方法?
- javascript - 将函数传递给使用 webpack 导入类的 web worker
- laravel - 控制器中的指令“有时”执行多次而不是 Laravel 中的一次
- javascript - 如何修复 React 中的组件错误“./src/components/App.js 'Layout', 'Home' is not defined react/jsx-no-undef
- python - 使用 Vagrant 和 Docker 运行 Python SSH 单元测试
- javascript - 为什么我的循环在 JavaScript 中不起作用?
- asp.net - DateTimePicker 未出现在工具箱中
- python - 如何将元素插入到任意深度的空列表嵌套列表中
- excel - 使用什么:COUNTIF 或 Vlookup 或组合或其他?
- apache-spark - Kubernetes 中的 Spark 作业卡在 RUNNING 状态