"한국 경제 사이트의 산업 탭에 존재하는 뉴스 기사들의 제목, 링크, 본문 데이터를 가져와 엑셀 파일로 변환하여 로컬 컴퓨터에 저장"
웹 스크래이핑 대상: 한국 경제/산업 탭 내 산업 전체 뉴스의 1 ~ 10 페이지
전체 소스코드
import pandas as pd
from bs4 import BeautifulSoup
import requests
# 페이지 이동
url = "https://www.hankyung.com/industry?page="
data = []
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}
for i in range(1, 10 + 1): # 1 ~ 10 페이지까지
res = requests.get(url + str(i), headers=headers)
html = res.text
soup = BeautifulSoup(html, "html.parser")
for i in range(30): # 한 페이지당 30개의 기사 존재
title = soup.select('.txt-cont > h3.news-tit')[i].text.strip() # 제목
link = soup.select('.txt-cont > h3.news-tit > a')[i]['href'] # 링크
desc = soup.select('.txt-cont > p.lead')[i].text.strip() # 간략한 본문
print("제목:", title)
print("링크:", link)
print("본문:", desc)
data.append([title, link, desc]) # 리스트 형식으로 제목, 링크, 본문 추가
data01 = ["제목", "링크", "본문"] # 헤더 부분
df = pd.DataFrame(data, columns=data01) # 데이터 프레임 생성
df.to_excel("news_result.xlsx") # xlsx 형식으로 저장
Result
'InfoSec Log > Python' 카테고리의 다른 글
[Python] 메모장 기능 구현 (0) | 2024.04.13 |
---|---|
[Python] 구글 이미지 웹 스크래핑 (0) | 2024.04.13 |
[Python] 로또 번호 Generator (1) | 2024.04.13 |
[Python] QR 코드 생성 (0) | 2024.04.10 |
[Python] 코스피, 코스닥 모든 상장 기업 데이터 스크래핑 (0) | 2024.04.06 |