Python 웹 스크래핑 프로젝트
Python 웹 스크래핑 프로젝트입니다. sample.html, BeautifulSoup 파서, CSV 저장, 프로젝트 구조와 허가된 대상 기준의 확장 방향을 정리했습니다.
Python 웹 스크래핑 프로젝트
이 프로젝트의 목표는 Python으로 웹 페이지를 가져오고, 필요한 요소를 추출한 뒤, CSV 파일로 저장하는 전체 흐름을 만드는 것이다. 실제 사이트를 무작정 수집하기보다 먼저 로컬 HTML로 구조를 고정하고, 이후 허가된 테스트 대상에 적용한다.
프로젝트 구조
scraping-project/
├── main.py
├── sample.html
└── output.csvsample.html
<!doctype html>
<html lang="ko">
<body>
<article class="post">
<h2>Linux 기초</h2>
<a href="/linux-basic">read</a>
</article>
<article class="post">
<h2>Python 기초</h2>
<a href="/python-basic">read</a>
</article>
</body>
</html>main.py
import csv
from pathlib import Path
from bs4 import BeautifulSoup
BASE_URL = "https://devmes.example"
def parse_posts(html: str) -> list[dict]:
soup = BeautifulSoup(html, "html.parser")
rows = []
for post in soup.select("article.post"):
title = post.select_one("h2").get_text(strip=True)
href = post.select_one("a")["href"]
rows.append({"title": title, "url": BASE_URL + href})
return rows
def save_csv(rows: list[dict], path: Path) -> None:
with path.open("w", newline="", encoding="utf-8") as fp:
writer = csv.DictWriter(fp, fieldnames=["title", "url"])
writer.writeheader()
writer.writerows(rows)
if __name__ == "__main__":
html = Path("sample.html").read_text(encoding="utf-8")
posts = parse_posts(html)
save_csv(posts, Path("output.csv"))
print(posts)실행
python3 -m venv .venv
. .venv/bin/activate
python -m pip install beautifulsoup4
python main.py
cat output.csv확장 방향
- 외부 요청은
requests.get(..., timeout=10)처럼 timeout을 둔다. - 수집 전 robots.txt와 이용약관을 확인한다.
- selector가 깨졌을 때 빈 값이 들어가지 않도록 예외 처리를 추가한다.
- 수집 결과는 CSV, JSON, SQLite 중 목적에 맞게 저장한다.