【问题标题】:Rvest binding all comments from forum thread into one data.frameRvest 将论坛线程中的所有评论绑定到一个 data.frame
【发布时间】:2018-08-03 10:20:53
【问题描述】:

我想收集对 data.frame 的论坛评论。 我想将所有评论从一个 url 收集到一行。评论的数量将不相等(最大评论 = 3),所以我想在没有评论的任何单元格中获得“NA”。

   library(rvest)
    library(xml2)
    library(qdapRegex)
    url_page <- c("http://medyczka.pl/forum-gastrologiczne/")
    web <- read_html(url_page)
    post_url <- web %>% html_nodes(css='.title') %>%
      html_attr('href') %>%
      as.character()
    post_url <-data.frame(post_url)

#Prepare df for all possible commentaries
posts_all <-data.frame()
#Let' make a simple function
for(i in 1:5){
  web2<-read_html(as.character(post_url[i,1]))
  posts <- web2 %>% html_nodes(css='.restore') %>%
    html_text() %>%
    as.character()
  posts <- rm_between(posts,'\r','\t', replacement="")
  posts_df <-data.frame(posts)
  posts_all <-rbind(posts_all,posts_df)
}
str(posts_all)

但是,我得到 1 列 92 行,而不是 5 行,最多 30 个评论(列)。

#> str(posts_all)
#'data.frame':  92 obs. of  1 variable:
 #$ posts: Factor w/ 89 levels "Do tego potrzeba wiedzy a tu nie ma lekarzy. Radzę zapytać na innym forum medycznym.",..: 14 4 11 3 1 6 12 2 7 10 ...

我做错了什么?如何正确收集数据?

【问题讨论】:

    标签: r for-loop dataframe web-scraping rvest


    【解决方案1】:

    我建议您查看tidyverservest。 这对你来说应该是一个很好的开始;

    library(tidyverse)
    library(rvest)
    
    pg <- read_html('http://medyczka.pl/forum-gastrologiczne/')
    
    tbl <- tibble(
            title = pg %>% html_nodes('.title') %>% html_text(),
            title_link = pg %>% html_nodes('.title') %>% html_attr('href')
            )
    
    get_comment <- function(url) {
    
    pg <- read_html(url)
    tbl <- tibble( posts = pg %>% html_nodes('.restore') %>% html_text() %>% str_trim(),
                   link = url
                    ) %>% mutate(post_seq = seq_along(posts))
    }
    
    posts_all <- NULL
    
    posts_all <-  map(tbl$title_link, get_comment) %>% bind_rows()
    
    tbl_posts_all <- tbl %>% left_join(posts_all, by = c('title_link' = 'link'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      相关资源
      最近更新 更多