【问题标题】:Web Scraping interactive map (javascript) with R and PhantomJS使用 R 和 PhantomJS 抓取 Web Scraping 交互式地图(javascript)
【发布时间】:2020-03-15 14:57:16
【问题描述】:

我正在尝试从交互式地图中抓取数据(希望获取某个县的犯罪数据)。我正在使用 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 r xml web-scraping phantomjs


    【解决方案1】:

    本网站使用 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 表示故意破坏,等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2015-08-12
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多