-3

我想使用 R 中的 Rvest 包从该酒店主页上抓取所有用户评论。

我只能检索前 10 条评论。通过单击由 JavaScript 生成的“查看更多”按钮来加载下一组评论。

我编写了以下 JavaScript - 'basic.js':

var webPage = require('webpage');
var page = webPage.create();

var fs = require('fs');
var path = 'taj.html'

page.open('http://www.holidayiq.com/Taj-Exotica-Benaulim-hotel-2025.html', function (status) {
  var content = page.content;
  fs.write(path,content,'w')
  phantom.exit();
});   

然后,我在 R 中使用了以下命令:

system("./phantomjs basic.js")

输出“taj.html”文件没有所有评论。所以,抓取代码...

pg <- read_html("taj.html")
pg %>% html_nodes(".detail-review-by-hotel .srm") %>% html_node(".media-heading") %>%   html_text()

... 仅返回前 10 条评论。

4

1 回答 1

1

使用 RSelenium:

library(RSelenium)
checkForServer() #just the first time
startServer()
startServer(invisible = FALSE, log = FALSE)
remDr <- remoteDriver(remoteServerAddr = "localhost" 
                  , port = 4444
                  , browserName = "chrome"
)
remDr$open()

导航到您的页面

remDr$navigate("http://www.holidayiq.com/Taj-Exotica-Benaulim-hotel-2025.html")

单击“查看更多”按钮,直到有东西可以按下(完成后手动停止执行)

while(TRUE){
webElem <- remDr$findElement(using = 'css selector', "#loadMoreTextReview")
remDr$mouseMoveToLocation(webElement = webElem) # move mouse to the element we selected
remDr$click(1) # 2 indicates click the right mouse button
}

使用 css 选择器刮掉你需要的一切(语法类似于 Rvest)

namesNodes <- remDr$findElements(using = 'css selector', "#result-items .media-heading")
names<-unlist(lapply(namesNodes, function(x){x$getElementText()}))

firstCommentNodes <- remDr$findElements(using = 'css selector', ".featured-blog-clicked") # the second element is the css selector
firstComment<-unlist(lapply(firstCommentNodes, function(x){x$getElementText()}))

reviewNodes <- remDr$findElements(using = 'css selector', ".detail-posted-txt p") # the second element is the css selector
review<-unlist(lapply(reviewNodes, function(x){x$getElementText()}))

我建议阅读选择器小工具小插图以了解如何选择 css 路径 -> ftp://cran.r-project.org/pub/R/web/packages/rvest/vignettes/selectorgadget.html

于 2016-03-23T01:38:51.817 回答