先前曾發文,介紹如何使用Python爬取駕駛距離。這次,介紹R的爬蟲方法。

依然分為兩步:第一步,爬取經緯度;第二步,依據經緯度爬取距離。

假設我們要獲取南京到上海的距離,首先獲取兩地的坐標。

library(xml2)
library(rvest)
library(dplyr)
library(stringr)
library(rjson)
library(jsonlite)
# 下面設置函數
coords = function(i) {
key = 你的高德密鑰
address = i # 以城市名為自變數
url = str_c(https://restapi.amap.com/v3/geocode/geo?key=,key,&address=,address)
data = read_html(url, encoding=utf-8) %>% html_text()
df = as.data.frame(fromJSON(data)) # 將json格式轉化為R的格式
return (df[geocodes.location]) # 返回該值
}
coords(南京市) # 獲得南京市的坐標
coords(上海市) # 獲得上海市的坐標

在RStudio中,顯示結果如下:

進而根據所得的坐標,計算兩地駕駛距離。

# 載入的包同上
# 下面設置函數
distance = function(i) {
key = 你的高德密鑰
origins = i # 起始點坐標
destination = 121.473701,31.230416 # 以上海市為目的地
type = 1 # type=0或1,分別為直線或駕駛距離
url = str_c(https://restapi.amap.com/v3/distance?key=,key,&origins=,origins,&destination=,destination,&type=,type)
data = read_html(url,encoding=utf-8) %>% html_text()
df = as.data.frame(fromJSON(data)) # 將json格式轉為R的格式
return (df[results.distance]) # 返回該值
}
distance(118.796877,32.060255) # 填入南京市坐標,爬取南京到上海的駕駛距離

在RStudio中,顯示結果如下:

至於實際情況如何呢?我們可以使用高德地圖來檢驗。如下圖所示:

檢驗結果,請看方案一。

如果需要測試兩地直線距離,只需要把type=1換成0即可,其餘不需要變動。

至於批量處理,需要設置函數與循環,本人不贅述。

國服帥座,寫於國慶。

次日修改。

推薦閱讀:

查看原文 >>
相關文章