Skip to content

Instantly share code, notes, and snippets.

@keizie
Last active June 8, 2018 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keizie/87f4830983bc4a42dfdd8e96a57f69a3 to your computer and use it in GitHub Desktop.
Save keizie/87f4830983bc4a42dfdd8e96a57f69a3 to your computer and use it in GitHub Desktop.
네이버 맵이 너무 웹페이지 출력에 맞춰져서 URL 호출만으로는 사용할 수 없는 바람에 만들어본 샘플
'use strict';
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('적당한URL', { waitUntil: 'networkidle2' });
await page.addScriptTag({
// 대량으로 호출해야 한다면 파일로 저장하고 path 옵션으로 추가하는 방식도 가능해보임
url: 'https://openapi.map.naver.com/openapi/v3/maps.js?clientId=네이버지도API키&submodules=geocoder'
});
await page.addScriptTag({ // 자동으로 추가되어야 할 것 같은데 안 되어서 수동으로 추가
url: 'https://openapi.map.naver.com/openapi/v3/maps-geocoder.js'
});
let mapX=127.1052133, mapY=37.3595316;
//mapX=114.06078815460204, mapY=22.54022639903853; // 중국 좌표는 실패하고, 대기가 끝나지 않음
await page.evaluate((lat, lng) => { // evaluateHandler은 DOM element만 반환하는 것으로 보이고, naver.maps 객체를 가져오지는 못하였음
window.globalVar = {}; // 네이버 API가 반환값을 주지 않고 콜백으로 처리되므로 콜백 안에서 값을 받아 기억하는 변수 사용
// 아래는 네이버 문서 샘플 코드
naver.maps.Service.reverseGeocode({
location: new naver.maps.LatLng(lat, lng),
}, function(status, response) {
if (status !== naver.maps.Service.Status.OK) {
return alert('Something wrong!');
}
var result = response.result, // 검색 결과의 컨테이너
items = result.items; // 검색 결과의 배열
// do Something
window.globalVar = result;
document.body.innerHTML = JSON.stringify(result); // 스크린샷 대응용
});
}, mapY, mapX);
// reverseGeocode 동작이 실제로는 JSONP 호출이어서 완료될 때까지 대기
await page.waitFor(1000);
const result = await page.evaluate(() => {
return JSON.stringify(window.globalVar); // 앞에서 기억해둔 반환값을 puppeteer 밖으로 가져옴
});
console.log(result); // 가져온 JSON이 화면에 출력됨
//await page.screenshot({path: 'screenshot.png'});
await browser.close();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment