javascript - 使用 R 和 PhantomJS 进行网页抓取交互式 map (javascript)

标签 javascript r xml web-scraping phantomjs

我正在尝试从交互式 map 中抓取数据(希望获取一个县的犯罪数据)。我正在使用 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")

接收我想要抓取的网址的函数

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 脚本中时继续进行的帮助(?)

谢谢!

最佳答案

该站点使用 JavaScript 向服务器进行查询。一种解决方案是重现其余请求并直接读取返回的 JSON 文件。这避免了使用 Phantomjs 的需要。

从浏览器的开发人员工具选项中并查看 xhr 文件,您将找到一个名为“query”的文件,其链接类似于:“https://gisapi.adacounty.id.gov/arcgis/rest/services/CrimeMapper/CrimeMapperWAB/FeatureServer/11/query?f=json&where=1%3D1&returnGeometry=true&spatialRel=esriSpatialRelIntersects&outFields= *&outSR=102100&resultOffset=0&resultRecordCount=1000”

直接读取此 JSON 响应并使用 jsonlite 包转换为列表:

library(jsonlite)
output<-jsonlite::fromJSON("https://gisapi.adacounty.id.gov/arcgis/rest/services/CrimeMapper/CrimeMapperWAB/FeatureServer/11/query?f=json&where=1%3D1&returnGeometry=true&spatialRel=esriSpatialRelIntersects&outFields=*&outSR=102100&resultOffset=0&resultRecordCount=1000")
output$features

找到链接中的第一个数字(本例中为 11)“FeatureServer/11/query?f=json”。该数字将确定查询服务器的犯罪行为。我发现,它可以取0到11之间的值。纵火输入0,毒品输入4,破坏公物输入11等。

关于javascript - 使用 R 和 PhantomJS 进行网页抓取交互式 map (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60694209/

相关文章:

java - 请求澄清多线程环境中 TransformerFactory 的 XSLT Transformer

javascript - 在 Firefox 中将 HTML 插入 iframe 不会从服务器获取图像,但在 Chrome 中却可以。为什么会这样呢?

r - 将 "lines"命令与 R 中的对象向量一起使用

javascript - 在 : Internal database vs. git javascript 项目中管理 JSON 文件的架构

r - 通过排列进行多组测试

r - R 是否在启动时创建了太多线程

java.util.Date 到 XMLGregorianCalendar

xml - xslt中count属性的范围是多少?

javascript - 更改单击菜单项的样式表 asp.net 母版页

javascript - 在没有实例的情况下寻址 jQuery Google Maps 对象