Estoy extrayendo comentarios de usuarios de una variedad de sitios web (como reddit.com) y Youtube también es otra fuente jugosa de información para mí. Mi raspador existente está escrito en R:
# x is the url
html = getURL(x)
doc = htmlParse(html, asText=TRUE)
txt = xpathSApply(doc,
//body//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)]",xmlValue)
Esto no funciona con los datos de Youtube; de hecho, si miras la fuente de un video de Youtube como este, por ejemplo, encontrarás que los comentarios no aparecen en la fuente.
¿Alguien tiene alguna sugerencia sobre cómo extraer datos en tales circunstancias?
¡Muchas gracias!
Después de esta respuesta: R: rvest: raspando una página de comercio electrónico dinámica
Puede hacer lo siguiente:
devtools::install_github("ropensci/RSelenium") # Install from github
library(RSelenium)
library(rvest)
pJS <- phantom(pjs_cmd = "PATH TO phantomjs.exe") # as i am using windows
Sys.sleep(5) # give the binary a moment
remDr <- remoteDriver(browserName = 'phantomjs')
remDr$open()
remDr$navigate("https://www.youtube.com/watch?v=qRC4Vk6kisY")
remDr$getTitle()[[1]] # [1] "YouTube"
# scroll down
for(i in 1:5){
remDr$executeScript(paste("scroll(0,",i*10000,");"))
Sys.sleep(3)
}
# Get page source and parse it via rvest
page_source <- remDr$getPageSource()
author <- html(page_source[[1]]) %>% html_nodes(".user-name") %>% html_text()
text <- html(page_source[[1]]) %>% html_nodes(".comment-text-content") %>% html_text()
#combine the data in a data.frame
dat <- data.frame(author = author, text = text)
Result:
> head(dat)
author text
1 Kikyo bunny simpie Omg I love fluffy puff she's so adorable when she was dancing on a rainbow it's so cute!!!
2 Tatjana Celinska Ciao 0
3 Yvette Austin GET OUT OF MYÂ HEAD!!!!
4 Susan II Watch narhwals
5 Greg Ginger who in the entire fandom never watched this, should be ashamed,\n\nPFFFTT!!!
6 Arnav Sinha LOL what the hell is this?
Comentario 1: Necesita la versión de github, consulte rselenium | obtener la fuente de la página de youtube
Comentario 2: este código le da los 44 comentarios iniciales. Algunos comentarios tienen un enlace "mostrar todas las respuestas" en el que debería hacer clic. Además, para ver aún más comentarios, debe hacer clic en el botón Mostrar más en la parte inferior de la página. El clic se explica en este excelente tutorial de RSelenium: http://cran.r-project.org/web/packages/RSelenium/vignettes/RSelenium-basics.html
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras