【发布时间】: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