네이버 증권 웹 크롤링

조회수 2297회

안녕하세요! 코딩초보입니다. 요 며칠간 네이브 증권사이트에서 주식데이타를 스크레이핑 하려했지만 계속해서 뜨는 에러때문에 많이 애를 먹었습니다.. 도와주시면 정말 감사하겠습니다ㅠㅠ

일단 크롤링 할 url은 https://finance.naver.com/item/sise_day.nhn?code=068270&page=1 이며 urlopen을 통해 가져와서 BeautifulSoup으로 읽습니다. 여기까지 프린트를 해보면 페이지를 찾을 수 없다, error_content 메시지를 보이며 주식정보가 출력되지 않습니다. 인코딩문제인가 생각해보았지만 딱히 해답을 찾지 못했습니다. 부탁드립니닷!

코드:

url = 'https://finance.naver.com/item/sise_day.nhn?code=068270&page=1'

with urlopen(url) as doc:
    html = BeautifulSoup(doc, 'lxml') 
    print(html)
    pgrr = html.find('td', class_='pgRR')
    s = str(pgrr.a['href']).split('=')
    last_page = s[-1]  

Output:

AttributeError: 'NoneType' object has no attribute 'a'
  • (•́ ✖ •̀)
    알 수 없는 사용자
  • pgrr 이 None 입니다. nowp 2021.2.10 12:58
  • 어느 모듈을 사용하는건지도 전부 올려주세요. 초보자 2021.2.10 13:55

1 답변

  • 다음부터는 사용하는 모듈까지 포함한 코드 전문을 올려주시기 바랍니다.

    html 출력시 다음과 같이 출력됩니다.

    이런 경우 selenium을 이용하거나, 다른 방법을 찾아야 합니다.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
    <title>네이버 :: 세상의 모든 지식, 네이버</title>
    <style type="text/css">
    .error_content * {margin:0;padding:0;}
    .error_content img{border:none;}
    .error_content em {font-style:normal;}
    .error_content {width:410px; margin:80px auto 0; padding:57px 0 0 0; font-size:12px; font-family:"나눔고딕", "NanumGothic", "돋움", Dotum, AppleGothic, Sans-serif; text-align:left; line-height:14px; background:url(https://ssl.pstatic.net/static/common/error/090610/bg_thumb.gif) no-repeat center top; white-space:nowrap;}
    .error_content p{margin:0;}
    .error_content .error_desc {margin-bottom:21px; overflow:hidden; text-align:center;}
    .error_content .error_desc2 {margin-bottom:11px; padding-bottom:7px; color:#888; line-height:18px; border-bottom:1px solid #eee;}
    .error_content .error_desc3 {clear:both; color:#888;}
    .error_content .error_desc3 a {color:#004790; text-decoration:underline;}
    .error_content .error_list_type {clear:both; float:left; width:410px; _width:428px; margin:0 0 18px 0; *margin:0 0 7px 0; padding-bottom:13px; font-size:13px; color:#000; line-height:18px; border-bottom:1px solid #eee;}
    .error_content .error_list_type dt {float:left; width:60px; _width /**/:70px; padding-left:10px; background:url(https://ssl.pstatic.net/static/common/error/090610/bg_dot.gif) no-repeat 2px 8px;}
    .error_content .error_list_type dd {float:left; width:336px; _width /**/:340px; padding:0 0 0 4px;}
    .error_content .error_list_type dd span {color:#339900; letter-spacing:0;}
    .error_content .error_list_type dd a{color:#339900;}
    .error_content p.btn{margin:29px 0 100px; text-align:center;}
    </style>
    </head>
    <!-- ERROR -->
    <body>
    <div class="error_content">
    <p class="error_desc"><img alt="페이지를 찾을 수 없습니다." height="30" src="https://ssl.pstatic.net/static/common/error/090610/txt_desc5.gif" width="319"/></p>
    <p class="error_desc2">방문하시려는 페이지의 주소가 잘못 입력되었거나,<br/>
                    페이지의 주소가 변경 혹은 삭제되어 요청하신 페이지를 찾을 수 없습니다.<br/>
                    입력하신 주소가 정확한지 다시 한번 확인해 주시기 바랍니다.
            </p>
    <p class="error_desc3">관련 문의사항은 <a href="https://help.naver.com/" target="_blank">고객센터</a>에 알려주시면 친절히 안내해드리겠습니다. 감사합니다.</p>
    <p class="btn">
    <a href="javascript:history.back()"><img alt="이전 페이지로" height="35" src="https://ssl.pstatic.net/static/common/error/090610/btn_prevpage.gif" width="115"/></a>
    <a href="https://finance.naver.com"><img alt="금융홈으로" height="35" src="https://ssl.pstatic.net/static/nfinance/btn_home.gif" width="115"/></a>
    </p>
    </div>
    </body>
    </html>
    

    제가 urllip을 이용한 크롤링을 할 줄 모르기때문에..

    requests 모듈을 사용하면 다음과 같이 해결할 수 있습니다.

    import requests
    from bs4 import BeautifulSoup
    
    url = 'https://finance.naver.com/item/sise_day.nhn?code=068270&page=1'
    headers = {#user agent}
    r = requests.get(url, headers = headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    tag = soup.select_one('td.pgRR > a')['href']
    sp = tag.split('=')
    print(sp)
    # ['/item/sise_day.nhn?code', '068270&page', '386']
    
    • 사용한 모듈은 bs4 그리고 urllib.request입니다. 초보님의 코드를 사용해보았는데 그래도 scraping한 html은 여전히 에러가 나네요ㅜㅠ 저도request.get을 포함한 여러가지 방식을 시도해보았지만 아직까지 해결이 안되고 있답니다. 혹시 네이버 측에서 웹트래픽 문제 방지차원에 막아 놓은건 아닌지... 그래도 답변 감사드립니다! 알 수 없는 사용자 2021.2.10 14:19
    • 정상적으로 작동하는 코드입니다. 헤더 부분 입력하고 해보세요. 그 정도는 찾아서 해보시라고 일부러 비워놓은 겁니다. 초보자 2021.2.10 15:12

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)