r - 如何使用 rvest 抓取网页的链接和文本?
问题描述
我正在尝试使用rvest
in来抓取阿根廷总统的演讲R
。这是我迄今为止编写的代码:
library(purrr)
library(rvest)
library(stringr)
url_president <- "https://www.casarosada.gob.ar/informacion/discursos?page=%d"
# extract relevant data on webpage
map_df(1:2, function(i) {
pg <- read_html(sprintf(url_president, i))
data.frame(
title = html_text(html_nodes(pg, ".category-item-title h3")) %>%
str_trim(),
date = html_text(html_nodes(pg, "time")),
link = html_elements(pg, css = ".category-item-title h3") %>% html_attr('href'),
stringsAsFactors = FALSE
)
}) -> argentina_speeches_pres
这会捕获演讲的标题和日期,但不会捕获链接(我想用它来抓取文本)。有人可以帮我解决这个问题吗?我不确定出了什么问题。
解决方案
您需要使用不同的 css 选择器来获取链接。尝试 -
library(rvest)
library(tidyverse)
url_president <- sprintf("https://www.casarosada.gob.ar/informacion/discursos?page=%d", 1:2)
map_df(url_president, function(i) {
pg <- read_html(i)
tibble(
title = html_nodes(pg, ".category-item-title h3") %>% html_text() %>% str_trim(),
date = html_nodes(pg, "time") %>% html_text() %>% str_trim(),
link = html_elements(pg, 'a.panel') %>%
html_attr('href') %>%
paste0('https://www.casarosada.gob.ar', .),
)
}) -> argentina_speeches_pres
argentina_speeches_pres
# A tibble: 80 x 3
# title date link
# <chr> <chr> <chr>
# 1 Palabras del presidente de la Nación, Albert… Jueves 11 de N… https://www.casarosada.gob.ar/informacion/d…
# 2 Palabras del presidente de la Nación, Albert… Viernes 05 de … https://www.casarosada.gob.ar/informacion/d…
# 3 Palabras del presidente de la Nación, Albert… Viernes 05 de … https://www.casarosada.gob.ar/informacion/d…
# 4 Palabras del presidente de la Nación, Albert… Jueves 04 de N… https://www.casarosada.gob.ar/informacion/d…
# 5 PALABRAS DEL PRESIDENTE DE LA NACIÓN, ALBERT… Miércoles 03 d… https://www.casarosada.gob.ar/informacion/d…
# 6 Palabras del presidente de la Nación, Albert… Martes 02 de N… https://www.casarosada.gob.ar/informacion/d…
# 7 Palabras del presidente de la Nación, Albert… Miércoles 27 d… https://www.casarosada.gob.ar/informacion/d…
# 8 Palabras del Presidente de la Nación, Albert… Miércoles 27 d… https://www.casarosada.gob.ar/informacion/d…
# 9 Palabras del presidente de la Nación, Albert… Miércoles 20 d… https://www.casarosada.gob.ar/informacion/d…
#10 Palabras del presidente de la nación, Albert… Miércoles 20 d… https://www.casarosada.gob.ar/informacion/d…
# … with 70 more rows
推荐阅读
- c# - 如何从签名邮件中获取 .msg 文件?
- powershell - 以有效的方式将哈希表转换回字符串数据
- react-native - 如何在 React-Native 中的抽屉导航中的屏幕之间传输数据
- java - 如何在没有 Eclipse 的情况下运行 Jsp 项目
- node.js - 上传大量文件时节点脚本导致系统冻结
- jquery - 带有 POSTMAN 的 asp.net 核心 API 工作正常,但使用 jquery ajax 不起作用?
- docker - Artifactory oss 与 Docker 一起安装
- ruby - 无法构建 gem 原生扩展(安装 ruby-debug-ide-0.7.1.beta3.gem)
- java - 排除 Maven 中的传递阴影依赖
- java - 使用 OSGI 将不同的提供者和消费者链接到一个消费者