본문 바로가기

공부방/Upstage AI Lab 4기

네이버 증권 데이터 크롤링 | f-string이 중요하네!! 디버깅 힌트

아래 코드에서 틀린 점은?! 

import requests
from bs4 import BeautifulSoup

def crawl(code):

    url = "https://finance.naver.com/item/main.naver?code={code}"
    res = requests.get(url)
    bsobj = BeautifulSoup(res.text, "html.parser")
    
    #주가 뽑기
    div_today = bsobj.find("div", {"class":"today"})
    em = div_today.find("em")
    price = em.find("span").text
    
    #회사이름 뽑기 
    h_company = bsobj.find("div", {"class": "h_company"})
    name = h_company.a.text
    
    #종목코드 뽑기
    div_discription = h_company.find("div", {"class":"description"})
    code = div_discription.span.text

    #거래량 뽑기
    table_no_info = bsobj.find("table", {"class":"no_info"})
    tds = table_no_info.tr.find_all("td")
    trading_volume =tds[2].find("span", {"class":"blind"}).text
    
    # 뽑은 데이터를 딕셔너리로 만들기
    dic = {"price": price, "name":name, "code":code, "volume":trading_volume}

    return(dic)

참고로 이거 붙잡고 계속 끙끙 앓았다 대체 왜 안되나..... 자꾸 Attribute Error가 나서. 대체 왜 안되나...

ㅂㄷㅂㄷ

중간에 프린트를 넣어주면서 무슨 attribute가 빠졌다는건지 확인했는데, 

def crawl(code):

    url = "https://finance.naver.com/item/main.naver?code={code}"
    res = requests.get(url)
    bsobj = BeautifulSoup(res.text, "html.parser")
    print(bsobj)

코드가 안들어간 것을 볼 수 있다. 코드가 제대로 안들어갔네.

코드를 f-스트링으로 넣었어야하는데 잘못한거였다.

url = f"https://finance.naver.com/item/main.naver?code={code}"

 

이제 이런 실수하지 말아야지

그래서 굳이 남기는 기록