개발

🕷Data Crawling 2

gyeomii 2023. 8. 22. 18:50
반응형

매일경제 주식 시세 사이트 크롤링하기

Untitled

코드

import requests
from bs4 import BeautifulSoup

url = "https://vip.mk.co.kr/newSt/rate/item_all.php"

response = requests.get(url)

if response.status_code == 200:
    html = response.content.decode('euc-kr','replace')
    soup = BeautifulSoup(html, 'html.parser')
    attr1 = {'class' : 'st2', 'width' : '92'}
    tds = soup.find_all('td', attrs = attr1)
    #attr2 = {'width':'60'}
    #price = soup.find_all('td', attrs= attr2)
    for idx, td in enumerate(tds):
        s_name = td.text
        s_price = td.parent.find_all("td")[1].text
        s_code = td.a['title']
        print(idx, s_code, s_name, s_price)

else : 
    print(response.status_code)
  • 주식의 이름을 먼저 가져와야 하기 때문에 td중에 class명이 st2인 td를 선택
attr1 = {'class' : 'st2', 'width' : '92'}
tds = soup.find_all('td', attrs = attr1)

결과

반응형