Python/Python_Crawling
특정 영역의 하위태그별 데이터 크롤링
Mr.DonyStark
2024. 1. 28. 23:09
□ 아래 그림 참고요망
□ 코스피 텝에서 표시되는 모든 회사명, 회사별 코스피가격, 증감률 데이터 추출
□ 코스피 텝, 즉, 상위 태그안에서의 데이터들 중 회사명, 코스피가격, 증감률에 해당하는 클래스 네임과 For문을 활용해 추출 및 출력
#라이브러리 호출
import requests
import re
from bs4 import BeautifulSoup
#크롤링대상사이트 및 request/get 요청
req_site = requests.get('크롤링사이트')
soup_parser = BeautifulSoup(req_site.content, 'html.parser')
get_data = soup_parser.select('.row_sty') #클래스네임이 row_sty 영역의 데이터 요청
#회사명과 주가 한줄로 출력
#위에서 지정한 상위태그 클래스명이 row_sty로부터 get한 데이터들 중 클래스명이 st_name, st_price, st_rate인 데이터들만 추출
for index, v1 in enumerate(get_data):
companv_nm = v1.select_one('.st_name').get_text().strip() #클래스네임이 row_sty 영역안에서 기업명 클래스네임 st_name 출력
company_prc = v1.select_one('.st_price').get_text().strip().replace(',','') #클래스네임이 row_sty 영역안에서 주가 클래스네임 st_price 출력 / 금액 인트형전환을 위해 천원단위 콤마(,) 공백으로 대체
updown_percent = float(v1.select_one('.st_rate').get_text().strip().replace(' ','').replace('%','')) #클래스네임이 row_sty 영역안에서 주가 클래스네임 st_rate 출력
yesterday_prc = int(int(company_prc) / (1 + (updown_percent / 100)))
print(f'□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n{index} 번째 기업은 {companv_nm} 으로 주가는 {company_prc} 원 입니다.\n전날 주가 : {yesterday_prc} 원 입니다.\n전날대비 증감률 : {updown_percent} % 입니다.')