javascript - 在 Mac 上的 R 中调用 PhantomJS

标签 javascript r phantomjs

我正在尝试抓取一些使用 javascript 呈现的数据。我想尝试走 phatomjs 路线,但在从 R 中调用 phantomjs 时遇到了一些问题。

我下载了 phatomjs,将文件放在我的工作目录中,并尝试运行以下找到的代码 here :

library(rvest)

url <- "http://64px.com/instagram/"

# write out a script phantomjs can process

writeLines(sprintf("var page = require('webpage').create();
page.open('%s', function () {
    console.log(page.content); //page source
    phantom.exit();
});", url), con="scrape.js")

# process it with phantomjs

system("phantomjs scrape.js > scrape.html")

最后一条命令产生了这个错误:

sh: phantomjs: command not found

我做了一些搜索,这可能与我的 PATH 有关,但我听从了建议 here它仍然会抛出相同的错误。

sudo ln -s /phantomjs-2.0.0-macosx/bin/phantomjs /usr/local/bin/

知道为什么找不到 phantomjs 可执行文件吗?

谢谢。

类(class)信息:

R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.2 (El Capitan)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] ggvis_0.4.2     knitr_1.11      dplyr_0.4.3     plyr_1.8.3      stringr_1.0.0   rvest_0.2.0    
 [7] magrittr_1.5    RSelenium_1.3.5 XML_3.98-1.3    RJSONIO_1.3-0   RCurl_1.95-4.7  bitops_1.0-6   
[13] pacman_0.3.0   

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.1     xtable_1.7-4    R6_2.1.1        httr_1.0.0      highr_0.5       caTools_1.17.1 
 [7] tools_3.2.2     parallel_3.2.2  DBI_0.3.1       htmltools_0.2.6 assertthat_0.1  digest_0.6.8   
[13] shiny_0.12.2    formatR_1.2     mime_0.3        evaluate_0.7.2  stringi_0.5-5   httpuv_1.3.3

最佳答案

不幸的是,64pix 站点没有对数据使用 XHR 请求,它填充了主页上的“顶部”列表。如果您执行以下操作,则可以避免系统调用并留在-R 中:

library(rvest)
library(V8)

url <- "http://64px.com/instagram/"
pg <- read_html(url)

script_data <- html_nodes(pg, "script")[[3]]
dat <- gsub("\\$\\(function.*$", "", html_text(script_data))

ctx <- v8()
ctx$eval(dat)
head(ctx$get("accounts"))
##        username followers followers_now
## 1     instagram  64131228      45251017
## 2  justinbieber  23817614      20279386
## 3 kimkardashian  23519002      22218039
## 4       beyonce  22207790      21375819
## 5  arianagrande  21748827      20219621
## 6   selenagomez  19572601      18456569

即定位创建数据的内联 <script> 部分,将其 trim 掉(否则 javascript 会出错),然后获取结果数据。这是一些额外的侦探工作,但比使用 phantomjs 尤其是 Selenuim 轻得多。

关于javascript - 在 Mac 上的 R 中调用 PhantomJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34566346/

相关文章:

javascript - 从 CLI 或 Web 调用时 PhantomJS 挂起

javascript - 如何在 extjs 小部件列中获取 rowIndex

php - 限制每秒/分钟发送联系表单电子邮件

r - 错误: stat_count() can only have an x or y aesthetic

R:如何:使用 gplot 和 geom_density 绘制 3d 密度图

javascript - 将 exec 的输出设置为 UTF-8

javascript - 将 AMPScript(ExactTarget 脚本语言)变量分配给我的 DOM 上的字段值?

javascript - 了解 map 和 join 以创建唯一数组

r - 如何使用 DT 包中的 renderDataTable() 格式化数据表的列?

javascript - PhantomJS不支持音频标签