LoginSignup
0
0

【備忘録】YahooローカルサーチAPIを叩くソース

Posted at
#キーワードから位置情報を取得するスクリプト
#2024/01/15 YahooローカルサーチAPIを利用

#install.packages("httr")
#install.packages("stringi")
library(httr)
library(XML)
library(stringi)
library(RCurl)
library(RJSONIO)

#ターゲットデータの読み込み
tranData <- read.csv("hogehoge.csv")

# Yahoo APIキー(自分のAPIキーを使用してください)
api_key <- "ここにAPIキーを入力"

#出力用データフレーム
writeDF <- data.frame()

for (i in 1:nrow(tranData)) {
  # 場所の名称
  location_code <- tranData[i,1]
  location_name <- tranData[i,2]  
  
  #ローカルサーチAPI 例:コンビニコード指定(抽出を絞るため)
  api_url <- sprintf(
    "https://map.yahooapis.jp/search/local/V1/localSearch?appid=%s&query=%s&ac=0205001",
    api_key, URLencode(location_code)
  )
  
  #APIの実行
  Encoding(api_url) <- "UTF-8"
  doc <- getURL(api_url) 
  
  #欲しいデータを文字列として強引に抜き取る
  #緯度経度の取得
  y <- strsplit(
  gsub("</Coordinates>.*","",gsub(".*<Coordinates>","",doc))
  ,",")[[1]][1]
  x <- strsplit(
    gsub("</Coordinates>.*","",gsub(".*<Coordinates>","",doc))
    ,",")[[1]][2]
  #店舗名称の取得
  storeName <- 
    gsub("</Name>.*","",gsub(".*<Name>hoge","hoge",doc))
  #住所の取得
  address <- 
    gsub("</Address>.*","",gsub(".*<Address>","",doc))
  #読み仮名の取得
  yomi <- 
    gsub("</Yomi>.*","",gsub(".*<Yomi>","",doc))
  
  writeDF <- rbind(writeDF,cbind(location_code,location_name,storeName,yomi,address,x,y))
  
  print(i)
}

#nrow(writeDF[is.na(writeDF$address),])$storeName <- NULL

#クレンジング
writeDF <- writeDF[!is.na(writeDF$address),]
writeDF$storeName <- gsub(".*<Name>","",writeDF$storeName)

#writeDF <- writeDF[is.na(writeDF$address),]
writeDF <- writeDF[is.na(writeDF$address),c("location_code","location_name")]
write.csv(writeDF,"geocording_result.csv",row.names = F)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0