我正在尝试从交互式地图中抓取数据(希望获取一个县的犯罪数据)。我正在使用 R (rvest) 并尝试使用 phantomjs。我是网络抓取的新手,所以我不太了解所有元素如何协同工作(试图到达那里)。
我认为我遇到的问题是,在我运行 phantomjs 并使用 R 的 rvest 包上传 html 后,我最终得到了更多脚本,并且 html 中没有明确的数据。我的代码如下。
writeLines("var url = 'http://www.google.com';
var page = new WebPage();
var fs = require('fs');
page.open(url, function (status) {
just_wait();
});
function just_wait() {
setTimeout(function() {
fs.write('cool.html', page.content, 'w');
phantom.exit();
}, 2500);
}
", con = "scrape.js")
一个接受我想要抓取的 url 的函数
s_scrape <- function(url = "https://gis.adacounty.id.gov/apps/crimemapper/",
js_path = "scrape.js",
phantompath = "/Users/alihoop/Documents/phantomjs/bin/phantomjs"){
# this section will replace the url in scrape.js to whatever you want
lines <- readLines(js_path)
lines[1] <- paste0("var url ='", url ,"';")
writeLines(lines, js_path)
command = paste(phantompath, js_path, sep = " ")
system(command)
}
执行js_scrape()函数并得到一个保存为“cool.html”的html文件
js_scrape()
我不明白接下来要做什么的是下面的 R 代码:
map_data <- read_html('cool.html') %>%
html_nodes('script')
我通过 phantomjs 在 HTML 中获得的输出又只是脚本。寻求有关如何在面对(在我看来)是 javascript 嵌套在 javascript 脚本中时继续进行的帮助(?)
谢谢你!