xpath - 在 R 中抓取 Youtube 评论

标签 xpath youtube web-scraping

我正在从一系列网站(如 reddit.com)中提取用户评论,而 Youtube 对我来说也是另一个多汁的信息来源。我现有的爬虫是用 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) 

这不适用于 Youtube 数据,事实上,如果你查看像 this 这样的 Youtube 视频的来源例如,您会发现注释没有出现在源代码中。

有没有人对如何在这种情况下提取数据有任何建议?

非常感谢!

最佳答案

按照这个答案:R: rvest: scraping a dynamic ecommerce page

您可以执行以下操作:

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?

评论 1:您确实需要 github 版本,请参阅 rselenium | get youtube page source

评论2:
此代码为您提供了最初的 44 条注释。一些评论有一个“显示所有答案”链接,必须点击。此外,要查看更多评论,您必须单击页面底部的显示更多按钮。
在这个优秀的 RSelenium 教程中解释了单击:
http://cran.r-project.org/web/packages/RSelenium/vignettes/RSelenium-basics.html

关于xpath - 在 R 中抓取 Youtube 评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224613/

相关文章:

python - 无法通过 Selenium(Python) 按类名找到 div

ios - 使用 YouTube 数据 API 和 Alamofire 时出错

javascript - Google + YouTube JS API 阻止框架访问跨源框架

python - BeautifulSoup4 soup.find ('tag' , text=re.compile ('my text' )) 仅有时有效

javascript - xPath - 从 anchor 链接中提取 href 的内容

python - xpath如何忽略<br>标签

R 中的 XML 包 - readHTMLTable 和多行类

youtube - 通过访问 token 访问YouTube channel 标题需要什么范围?

javascript - 如何使用 node.js 抓取需要身份验证的网站?

python-3.x - 我想从文本输入中提取第三行