簡體   English   中英

如何使用rvest抓取網頁的鏈接和文本?

[英]How to scrape link and text of webpages using rvest?

我正在嘗試使用R rvest抓取阿根廷總統的演講。 這是我迄今為止編寫的代碼:

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

這會捕獲演講的標題和日期,但不會捕獲鏈接(我想用它來抓取文本)。 有人可以幫我解決這個問題嗎? 我不確定出了什么問題。

您可以使用 -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM