首页 > 解决方案 > 如何在数据框中使用 R 中的循环来获取许多 URL 的内容?

问题描述

我创建了一个 data.frame,在其 5 列中包含一个新闻 url 列表(1.000 页)。我想获取每篇新闻文章/链接的内容。我试图在数据框中使用循环来抓取每个链接的内容,但结果我只得到了最后一个链接的内容。

    #Getting the dynamic URL using %d

    url_principal <- 'https://www.eltiempo.com/buscar/%d? 
    q=proceso+de+paz&publishedAt[from]=12-08-26&publishedAt[until]=16-12- 
    03&contentTypes[0]=article'

    #Reading through the pages and collecting website elements

    map_df(1:1000, function(i) {

   pagina <- read_html(sprintf(url_principal, i, '%s', '%s', '%s', '%s'))

   data.frame(titulo = html_text(html_nodes(pagina, ".title.page-link")),
             lead = html_text(html_nodes(pagina, ".epigraph.page-link")),
             section = html_text(html_nodes(pagina, ".category")),
             date = html_text(html_nodes(pagina, ".published-at")),
             link = str_trim(html_attr(html_nodes(pagina, ".title.page-link"), "href")),
                      stringsAsFactors=FALSE)
  }) -> noticias_completas

    #Adding https to the links
    news_complete_https <- gsub("^","https://www.eltiempo.com", 
    noticias_completas[1:1000, 5])
    news_complete_https<- data.frame(lapply(news_complete_https, 
    as.character), stringsAsFactors = FALSE)

    #Loop for getting the content of each link within the data frame
    for(i in noticias_completas_frame){
    text <- read_html(i)
    contenido<- text%>% html_nodes(".articulo-contenido")%>% html_text()%>% 
   as.character()
    } -> final

我应该如何获取所有 url 的内容而不仅仅是最后一个条目?除了循环之外,我还需要哪些其他选项来实现这一目标?

非常感谢您的帮助!

标签: rweb-scraping

解决方案


推荐阅读