커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
db에서 불러오는 과정에서 undefined가 뜹니다.
undefined주차
북마크
양*빈
댓글
3
추천
0
조회수
11
조회수
11
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


강의 관련은 아니고 5주차까지 하루만에 끝내고나서 그냥 제가 만들고 싶었던 것을 대충이나마 만들고 있습니다. 과정은 beautiful soup로 정보를 각각 가져와서 doc으로 db에 한꺼번에 저장한 후, fetch로 긁어와 html에 붙이는 작업이지만, db는 제대로 저장이 되는데 가져오는 과정에서 문제가 생깁니다. 원인은 살짝 알 것 같은데 해결 방안이 생각나지 않네요..


<원래 의도>

정보1 정보2


<오류로 생긴 현재상황(사진첨부)>

정보1 정보2(undefined)

정보1(undefined) 정보2


스파르타 즉문즉답



#app.py
import pymongo
import requests
from bs4 import BeautifulSoup


from pymongo import MongoClient
client = pymongo.MongoClient("mongodb+srv://sparta:test@cluster0.ij8bjcr.mongodb.net/?retryWrites=true&w=majority")
db = client.test


from flask import Flask, render_template, request, jsonify
app = Flask(__name__)


url = 'https://typhoon.yahoo.co.jp/weather/jp/earthquake/'
html = requests.get(url).text


soup = BeautifulSoup(html, 'html.parser')
trs = soup.select_one('#eqinfdtl > table')
img = soup.select_one('#earthquake-01 > img')['src']


for tr in trs:
    date = soup.select_one('tr:nth-child(1) > td:nth-child(2) > small').text
    singenchi = soup.select_one('tr:nth-child(2) > td:nth-child(2) > small > a').text
    magnitude = soup.select_one('tr:nth-child(4) > td:nth-child(2) > small').text
    depth = soup.select_one('tr:nth-child(5) > td:nth-child(2) > small').text
    saidai_shindo = soup.select_one('tr:nth-child(3) > td:nth-child(2) > small').text
    tsunami = soup.select_one('tr:nth-child(7) > td:nth-child(2) > small').text
    
doc = {
        'country':'일본',
        'date':date,
        'singenchi':singenchi,
        'magnitude':magnitude,
        'depth':depth,
        'saidai_shindo':saidai_shindo,
        'tsunami':tsunami,
        'image':img
    }


db.eqinfos.delete_many
db.eqinfos.insert_one(doc)


url = 'https://www.weather.go.kr/w/eqk-vol/search/korea.do'
html = requests.get(url).text


soup = BeautifulSoup(html, 'html.parser')
tags = soup.select_one('#excel_body')


for tag in tags:
    date1 = soup.select_one('tbody > tr:nth-child(1) > td:nth-child(2) > span').text
    location = soup.select_one('tbody > tr:nth-child(1) > td:nth-child(8) > span').text
    magnitude1 = soup.select_one('tbody > tr:nth-child(1) > td:nth-child(3) > span').text
    depth1 = soup.select_one('tbody > tr:nth-child(1) > td:nth-child(4) > span').text
    max_intensity = soup.select_one('tbody > tr:nth-child(1) > td:nth-child(5) > span').text
    img1 = soup.select_one('tbody > tr:nth-child(1) > td:nth-child(9) > a')['href']
    
doc = {
        'country':'국내',
        'date1':date1,
        'location':location,
        'magnitude1':magnitude1,
        'depth1':depth1,
        'max_intensity':max_intensity,
        'image1':img1
    }


db.eqinfos.insert_one(doc)


@app.route('/')
def home():
    return render_template('index.html')


@app.route("/earthquake", methods=["GET"])
def earthquake_get():
    all_eqinfos = list(db.eqinfos.find({},{'_id':False})) 
    return jsonify({'result':all_eqinfos})


if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)

#html
<!doctype html>
<html lang="en">


<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">


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>


    <title>지진정보</title>


    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }


        .title {
            margin: 0px auto 0px 150px;
            background-color: tomato;
            width: 320px;
            height: 50px;
            border-radius: 20px;


            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
        }


        .title1 {
            margin: -50px 150px 0px auto;
            background-color: blue;
            width: 320px;
            height: 50px;
            border-radius: 20px;
            color: white;


            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
        }


        .box {
            margin: 1px auto 0px 50px;
            background-color: gray;
            width: 500px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            color: white;
            padding: 10px;
            border-radius: 20px;
        }


        .box1 {
            margin: 1px auto 0px 90px;
            background-color: gray;
            width: 500px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            color: white;
            padding: 10px;
            border-radius: 20px;
        }


        .title:hover {
            background-color: brown;
        }


        .title1:hover {
            background-color: slateblue;
        }


        .img {
            margin: 0px auto 0px 60px;
            width: 500px;
            height: 400px;
        }


        .img1 {
            margin: 0px auto 0px 100px;
            width: 500px;
            height: 400px;
        }


        .koeqinfo {
            margin: -525px auto 0px 600px;
        }
    </style>
    <script>
        $(document).ready(function () {
            listing();
        });


        function listing() {
            fetch('/earthquake').then((res) => res.json()).then((data) => {
                let rows = data['result']
                $('#all_eqinfo').empty()
                rows.forEach((a) => {
                    let date = a['date']
                    let singenchi = a['singenchi']
                    let magnitude = a['magnitude']
                    let depth = a['depth']
                    let saidai_shindo = a['saidai_shindo']
                    let tsunami = a['tsunami']
                    let eqmap = a['image']
                    let date1 = a['date1']
                    let location = a['location']
                    let magnitude1 = a['magnitude1']
                    let depth1 = a['depth1']
                    let max_intensity = a['max_intensity']
                    let eqmap1 = a['image1']


                    let temp_html = `<div id="all_eqinfo">
                                        <div class="eqinfo">
                                            <div id="eqinfo">
                                                <p>
                                                    <img class="img"
                                                        src="${eqmap}">
                                                </p>
                                                <p class="box">
                                                    ${date}${singenchi}を震源とする地震がありました。 地震の規模は${magnitude}、震源の深さ${depth}、最大震度は${saidai_shindo}を観測されました。${tsunami}
                                                </p>
                                            </div>
                                            <div id="eqinfo1" class="koeqinfo">
                                                <p>
                                                    <img class="img1"
                                                        src="${eqmap1}">
                                                </p>
                                                <p class="box1">
                                                    ${date1}${location}에서 깊이 ${depth1}의 규모 ${magnitude1}의 지진이 있었습니다. 이 지진으로 ${max_intensity}의 최대진도를 기록했습니다.
                                                </p>
                                            </div>
                                        </div>
                                </div>`
                    $('#all_eqinfo').append(temp_html)
                })     
            })
        }


        function refresh() {
            setTimeout(play, 5000)
        }


        function refresh1() {
            setTimeout(play1, 5000)
        }


        function play() {
            if ('speechSynthesis' in window) {
                let working = new SpeechSynthesisUtterance($('#eqinfo').text())
                working.lang = 'ja-JP'
                working.pitch = 1
                working.rate = 1.2


                window.speechSynthesis.speak(working)
            }
            else {
                document.write("Browser not supported")
            }
        }


        function play1() {
            if ('speechSynthesis' in window) {
                let working1 = new SpeechSynthesisUtterance($('#eqinfo1').text())
                working1.lang = 'ko-KR'
                working1.pitch = 1
                working1.rate = 1.2


                window.speechSynthesis.speak(working1)
            }
            else {
                document.write("Browser not supported")
            }
        }
    </script>
</head>


<body>
    <div class="title">
        <h1 id="title" onclick="refresh(),listing()">最新の地震情報</h1>
    </div>
    <div class="title1">
        <h1 id="title1" onclick="refresh1(),listing()">최신 지진정보</h1>
    </div>
    <div id="all_eqinfo">
        <div class="eqinfo">
            <div id="eqinfo">
                <p>
                    <img class="img"
                        src="https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyMDAxMThfMjU3%2FMDAxNTc5MzQ4NTg1Mzgy.QGxdPRFAaIv15SH7cSA9xJ2vIkSU0rKG5Y_38v3DhCgg.LqA0EMr68b4wqRzmO2VZTQO9H0jpeAZF1yO_uaj40wkg.GIF.halowd%2Floading.gif&type=sc960_832_gif">
                </p>
                <p class="box">
                    2023年1月11日 16時24分ごろ宮城県北部を震源とする地震がありました。 地震の規模は3.8、震源の深さ80km、最大震度は1を観測されました。
                </p>
            </div>
            <div id="eqinfo1" class="koeqinfo">
                <p>
                    <img class="img1"
                        src="https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyMDAxMThfMjU3%2FMDAxNTc5MzQ4NTg1Mzgy.QGxdPRFAaIv15SH7cSA9xJ2vIkSU0rKG5Y_38v3DhCgg.LqA0EMr68b4wqRzmO2VZTQO9H0jpeAZF1yO_uaj40wkg.GIF.halowd%2Floading.gif&type=sc960_832_gif">
                </p>
                <p class="box1">
                    2023/01/09 01:28:15경 인천 강화군 서쪽 25km 해역에서 깊이 19km의 규모 3.7의 지진이 있었습니다. 이 지진으로 IV의 최대진도를 기록했습니다.
                </p>
            </div>
        </div>
    </div>
</body>


</html>


취소
 공유
취소
댓글 0
댓글 알림
나의얼굴