[2024-07-17] 개발일지 2일차(openpyxl)
# 잘된 거
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
from datetime import datetime
def get_news(keyword):
wb = Workbook()
sheet = wb.active
# headers 변수에 지정된 User-Agent 헤더는 HTTP 요청의 일종으로, 웹 서버에 요청을 보낼 때 클라이언트(웹 브라우저 또는 HTTP 클라이언트)의
정보(브라우저 종류, 버전, 운영 체제 등)를 포함하여 보냅니다.
이 정보를 통해 웹 서버는 요청이 어떤 브라우저나 클라이언트에서 왔는지 알 수 있습니다.
각 부분(mozilla,wubdiws nT,html, like Gecko etc..)은 클라이언트의 특정 정보를 나타냅니다:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
# URL 포맷팅 수정
url = f'http://13.125.227.101/finance_automation/?keyword={keyword}'
data = requests.get(url, headers=headers)
# HTTP 요청 성공 여부 확인
if data.status_code != 200:
print(f"Error: Received status code {data.status_code}")
return
soup = BeautifulSoup(data.text, 'html.parser')
# 선택자 수정
lis = soup.select('#main_pack > section > div > div.group_news > ul > li')
if not lis:
print("No news items found.")
return
for li in lis:
a = li.select_one('a.news_tit')
if a: # a 태그가 존재하는지 확인
row = [a.text, a['href']]
sheet.append(row)
else:
print("No 'a.news_tit' element found in list item.")
today = datetime.today().strftime('%Y-%m-%d')
# 엑셀 파일 저장
wb.save(f"{today}_{keyword}.xlsx")
wb.close()
get_news('삼성전자')
# 시간 추가
# from datetime import datetime
# datetime.today().strftime("%Y-%m-%d")
Comments
Post a Comment