네이버 지도 API를 신청해서
http://localhost:5000/map 로 뜨도록 설정
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>간단한 지도 표시하기</title>
<script type="text/javascript"
src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=mtjbr1c0cc"></script>
<script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
#map {
width: 100%;
height: 400px;
}
</style>
<script>
$(document).ready(function () {
let map = new naver.maps.Map('map', {
center: new naver.maps.LatLng(37.4981125, 127.0379399),
zoom: 10
});
})
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
@app.route('/map')
def test_map():
return render_template("prac_map.html")
위 이미지처럼..만들기...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>간단한 지도 표시하기</title>
<!-- 아래 부분이 id를 map으로 한 곳에 지도가 나오게 해주는 코드-->
<script type="text/javascript"
src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=mtjbr1c0cc"></script>
<script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
#map {
width: 100%;
height: 400px;
}
</style>
<script>
$(document).ready(function () {
let map = new naver.maps.Map('map', { //네이버에서 지도를 띄운다
center: new naver.maps.LatLng(37.4981125, 127.0379399), //이 위도,경도에 중앙값 두고
zoom: 10, //줌을 기본으로 10정도 주세용
zoomControl: true, //줌 기능을 켜준다
zoomControlOptions: {
style: naver.maps.ZoomControlStyle.SMALL,
position: naver.maps.Position.TOP_RIGHT
}
});
let marker = new naver.maps.Marker({ //지도에 마커를 띄운다
position: new naver.maps.LatLng(37.4981125, 127.0379399), //어느 위치에
map: map, //어느 지도에
icon: "{{ url_for('static', filename='rtan_heart.png') }}" //마커 이미지 바꾸기
});
let infowindow = new naver.maps.InfoWindow({ //정보창 띄운다
content: `<div style="width: 50px;height: 20px;text-align: center"><h5>안녕!</h5></div>`,
});
// infowindow.open(map, marker);//정보창 열겠다, 기존에 만든 맵에 마커를 기준으로
// infowindow.close(); //창이 닫힘
naver.maps.Event.addListener(marker, "click", function () { //네이버 맵에 이벤트 등록(어떤 행동을 하는지 항상 듣는 녀석)
// 마커에, 클릭 일어났을 때 아래 함수 실행하겠다
console.log(infowindow.getMap()); // 정보창이 열려있을 때는 연결된 지도를 반환하고 닫혀있을 때는 null을 반환
if (infowindow.getMap()) { //열려있으면 true
infowindow.close();
} else {
infowindow.open(map, marker);
}
});
})
</script>
</head>
<body>
<div id="map"></div> <!--여기서 지도 만들어짐-->
</body>
</html>
맛집 정보 DB에 저장하는 코드...
from selenium import webdriver
from bs4 import BeautifulSoup
import time
from selenium.common.exceptions import NoSuchElementException
from pymongo import MongoClient
import requests
client = MongoClient('3.35.24.64', 27017, username="test", password="test")
db = client.dbsparta_plus_week3
driver = webdriver.Chrome('./chromedriver') #셀레니움이 크롬드라이버를 잡아서
url = "http://matstar.sbs.co.kr/location.html" #맛집 페이지
driver.get(url) #url 데리고 와서
time.sleep(5)
#페이지 소스 로드하기 전에 더 많은 맛집정보 가져오기 위해, 더보기 선택자 만들기
# btn_more = driver.find_element_by_css_selector("#foodstar-front-location-curation-more-self > div > button") #css 선택자를 가지고 요소를 찾는다
# btn_more.click() #더보기 클릭
# time.sleep(5)
for i in range(10): #더보기 10번 누르기
try:
btn_more = driver.find_element_by_css_selector("#foodstar-front-location-curation-more-self > div > button")
btn_more.click()
time.sleep(5)
except NoSuchElementException: #try 코드 실행하다가 예외 발생시
break
req = driver.page_source #페이지 소스 로드
driver.quit()
soup = BeautifulSoup(req, 'html.parser')
places = soup.select("ul.restaurant_list > div > div > li > div > a") #카드의 선택자, places 안에 맛집 목록 저장
print(len(places))
for place in places:
title = place.select_one("strong.box_module_title").text #상점 간판 제목
address = place.select_one("div.box_module_cont > div > div > div.mil_inner_spot > span.il_text").text #식당 주소
category = place.select_one("div.box_module_cont > div > div > div.mil_inner_kind > span.il_text").text #식당의 카테고리
show, episode = place.select_one("div.box_module_cont > div > div > div.mil_inner_tv > span.il_text").text.rsplit(" ", 1)#몇 번째의 어떤 에피소드?
print(title, address, category, show, episode)
headers = {
"X-NCP-APIGW-API-KEY-ID": "mtjbr1c0cc",
"X-NCP-APIGW-API-KEY": "bnqCQTyNDQCRP8NWfkKnyhKEYkIlzRm8U4SxiEJh"
}
r = requests.get(f"https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query={address}", headers=headers) #쿼리 부분에 주소, requests.get요청시 headers로 보내준다
response = r.json()
if response["status"] == "OK": #ok라면
if len(response["addresses"]) > 0:
x = float(response["addresses"][0]["x"]) #그냥 꺼내면 문자열로 나와서 실수값으로
y = float(response["addresses"][0]["y"])
print(title, address, category, show, episode, x, y)
doc = { #DB 저장
"title": title,
"address": address,
"category": category,
"show": show,
"episode": episode,
"mapx": x,
"mapy": y}
db.matjips.insert_one(doc)
else:
print(title, "좌표를 찾지 못했습니다")
Project 03 참고!
'Today I Learned' 카테고리의 다른 글
2차 프로젝트 마무리_KPT (0) | 2021.10.19 |
---|---|
WIL1012 (0) | 2021.10.12 |
멜론 차트 / 네이버 이미지 주소 스크래핑 (0) | 2021.10.09 |
나만의 단어장 만들기 2 - Jinja2 (0) | 2021.10.08 |
나만의 단어장 만들기 - Ajax / Jinja2 (0) | 2021.10.08 |