我想创建一个爬虫,它会从 Trip Advisor 中抓取一些数据。理想情况下,它将 (a)识别到所有要抓取的位置的链接, (b)收集到每个位置的所有景点的链接,以及 (c)将收集所有评论的目的地名称、日期和评级。我现在想专注于(a)部分。
这是我开始的网站: http ://www.tripadvisor.co.nz/Tourism-g255104-New_Zealand-Vacations.html
这里有一个问题:该链接给出了前 10 个目的地,然后如果您单击“查看更多热门目的地”,它将展开列表。看起来好像它使用 javascript 函数来实现这一点。不幸的是,我不熟悉 javascript,但我认为以下部分可能会提供有关其工作原理的线索:
<div class="morePopularCities" onclick="ta.call('ta.servlet.Tourism.showNextChildPage', event, this)">
<img id='lazyload_2067453571_25' height='27' width='27' src='http://e2.tacdn.com/img2/x.gif'/>
See more popular destinations in New Zealand </div>
我为 R 找到了一些有用的网络抓取包,例如 rvest、RSelenium、XML、RCurl,但其中只有 RSelenium 似乎能够解决这个问题,话虽如此,我仍然无法使用它出去。
以下是一些相关代码:
tu = "http://www.tripadvisor.co.nz/Tourism-g255104-New_Zealand-Vacations.html"
RSelenium::startServer()
remDr = RSelenium::remoteDriver(browserName = "internet explorer")
remDr$open()
remDr$navigate(tu)
# remDr$executeScript("JS_FUNCTION")
最后一行应该在这里解决问题,但我不确定我需要在这里调用什么函数。
一旦我设法扩展此列表,我将能够以与解决部分 (b) 相同的方式获取每个目的地的链接,并且我认为我已经解决了这个问题(对于那些感兴趣的人):
library(rvest)
tu = "http://www.tripadvisor.co.nz/Tourism-g255104-New_Zealand-Vacations.html"
tu = html_session(tu)
tu %>% html_nodes(xpath='//div[@class="popularCities"]/a') %>% html_attr("href")
[1] "/Tourism-g255122-Queenstown_Otago_Region_South_Island-Vacations.html"
[2] "/Tourism-g255106-Auckland_North_Island-Vacations.html"
[3] "/Tourism-g255117-Blenheim_Marlborough_Region_South_Island-Vacations.html"
[4] "/Tourism-g255111-Rotorua_Rotorua_District_Bay_of_Plenty_Region_North_Island-Vacations.html"
[5] "/Tourism-g255678-Nelson_Nelson_Tasman_Region_South_Island-Vacations.html"
[6] "/Tourism-g255113-Taupo_Taupo_District_Waikato_Region_North_Island-Vacations.html"
[7] "/Tourism-g255109-Napier_Hawke_s_Bay_Region_North_Island-Vacations.html"
[8] "/Tourism-g612500-Wanaka_Otago_Region_South_Island-Vacations.html"
[9] "/Tourism-g255679-Russell_Bay_of_Islands_Northland_Region_North_Island-Vacations.html"
[10] "/Tourism-g255114-Tauranga_Bay_of_Plenty_Region_North_Island-Vacations.html"
至于步骤 (c),我发现了一些可能对此有所帮助的有用链接: https ://github.com/hadley/rvest/blob/master/demo/tripadvisor.R http://notesofdabbler.github。 io/201408_hotelReview/scrapeTripAdvisor.html
如果您对如何扩展热门目的地列表或如何以更智能的方式完成其他步骤有任何提示,请告诉我,我非常希望收到您的来信。
提前谢谢了!