如何使用Rvest和phantomJS从HolidayIQ获取所有酒店评论

时间:2016-03-22 11:00:50

标签: r phantomjs rvest rselenium

我想使用R中的Rvest包从这个hotel main page中删除所有用户评论。

我只能检索前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个评论。

1 个答案:

答案 0 :(得分: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路径 - &gt; ftp://cran.r-project.org/pub/R/web/packages/rvest/vignettes/selectorgadget.html