ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 네이버 뉴스 제목 크롤링하기
    Project/ML-파이썬 주식 종목 예측 2023. 6. 8. 12:35
    반응형
    import requests
    from bs4 import BeautifulSoup
    from urllib import parse
    
    price_data = pd.read_csv('samsung_주가데이터.csv')
    df_0 = price_data[price_data['price']==0]['Date']
    date_0 = []
    for i in range(0,len(df_0)):
        date_0.append(str(df_0.tolist()[i])[:10].replace('-','.'))
    df_1 = price_data[price_data['price']==1]['Date']
    date_1 = []
    for i in range(0,len(df_1)):
        date_1.append(str(df_1.tolist()[i])[:10].replace('-','.'))
    result_list = []
    error_cnt = 0
    
    def naver_news_title(dates) :
      base_url = 'https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EC%82%BC%EC%84%B1%EC%A0%84%EC%9E%90&sort=0&photo=0&field=0&pd=3&ds={}&de={}&cluster_rank=33&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:from{}to{},a:all&start={}'
      headers = {
              'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'
          }
      
      for date in dates :
        for i in range(0,40,10) :
          url = base_url.format(date,date,date.replace('.',''),date.replace('.',''),i)
          res = requests.get(url, headers=headers)
          if res.status_code == 200:
            soup = BeautifulSoup(res.text)
            title_list = soup.select('ul.list_news li')
            for title in title_list :
              try :
                if title.select_one('a.news_tit') == None :
                  continue
                news_title = title.select_one('a.news_tit').text.strip()
                result_list.append([news_title])
              except :
                error_cnt += 1

    코드부터 가져와서 설명하겠다

    전에 글에서 만든 주가데이터에 전날 가격에 따른 상승 하강 속성인 price를 추가해서 csv로 저장해주었다.

    그리고 Pirce속성을 바탕으로 상승한 날짜와 하락한 날짜의 date를 구분하여 2개의 배열로 저장해주었다.

     

    naver_news_title함수는 dates를 전달받아 순회하며 title을 result_list에 저장한다.

    date for문 안에 있는 i는 뉴스의 갯수이며 삼성전자와 연관된 뉴스들이 너무 많아서 관련도 높은 순으로 조회한

    상위 30개의 목록을 담기 위해 반복문을 추가했다.

     

    나는 a.news_tit에 적힌 text를 추출했찌만 none값인 경우도 많이 있어서 해당 부분은 가볍게 pass해주고 title이 있는 경우에만 result에 추가해주었다. 이렇게만 해도 많은 데이터를 얻을 수 있다.

     

    구글 코랩에서 실행한 결과인데 주가 변동에 대한 속성도 잘 나오고 뉴스 기사도 올바르게 크롤링 된 것을 볼 수 있다.

    반응형

    'Project > ML-파이썬 주식 종목 예측' 카테고리의 다른 글

    머신러닝 모델 수정  (0) 2023.06.09
    머신러닝 모델 만들기 및 테스트  (2) 2023.06.09
    주식 데이터 가져오기  (0) 2023.06.06
    AI학습에 관하여  (0) 2023.06.05
    function connect Error  (0) 2023.06.05

    댓글

Designed by Tistory.