taro
crawl.py
rabbit-jun
2026. 4. 9. 20:52
1️⃣ resp.text와 html.parser
resp = requests.get(url) # requests 라이브러리에서 나온 Response 객체
soup = BeautifulSoup(resp.text, 'html.parser')
- resp.text: requests 라이브러리의 Response 객체 속성 → HTTP 응답의 HTML 문자열
- html.parser: BeautifulSoup에 내장된 파서 → HTML 문자열을 구조화된 트리로 변환
2️⃣ CSS 선택자 구조
items = soup.select('.inner .post-item a')
- .inner: class="inner" 태그 찾기
- .post-item: 그 안의 class="post-item" 찾기
- a: 그 안의 태그 찾기
HTML 예제:
<div class="inner">
<div class="post-item">
<a href="/post1">타로카드 1번</a>
</div>
</div>
반환값: 태그들의 리스트
3️⃣ select_one() vs select()
# select_one: 첫 번째 매칭 요소만 반환
title_tag = soup.select_one('h2 b') # 하나의 요소
# select: 모든 매칭 요소를 리스트로 반환
items = soup.select('.inner .post-item a') # 여러 요소의 리스트
4️⃣ HTML 구조 확인
# prettify()로 들여쓰기된 HTML 출력
print(soup.prettify())
5️⃣ find_all() 메서드
# 해당 태그들을 모두 검색해서 리스트로 반환
for p in content_area.find_all(['p', 'h2', 'h4']):
text = p.get_text()
6️⃣ get_text() 메서드
# HTML의 모든 텍스트만 추출 (태그 제거)
text = p.get_text()
# 예제
html = "<p>안녕하세요. <b>진하게</b> 된 텍스트입니다.</p>"
text = soup.p.get_text()
# 결과: "안녕하세요. 진하게 된 텍스트입니다."
- 특징: 하위 태그들도 포함해서 텍스트만 추출
7️⃣ 상태 머신 로직 (State Pattern)
current_mode = "공통" # 초기 상태
for p in content_area.find_all(['p', 'h2', 'h4']):
text = p.get_text().strip()
# 상태 전환 트리거
if "1. 정방향" in text:
current_mode = "정방향"
current_sub = None
continue
elif "2. 역방향" in text:
current_mode = "역방향"
current_sub = None
continue
# 세부 항목 처리 (정/역방향 모드일 때만)
if current_mode in ["정방향", "역방향"]:
if "① 해석" in text: current_sub = "해석"
elif "② 사랑" in text: current_sub = "사랑"
# ...
# 데이터 저장
if current_mode == "공통":
result["공통해석"] += text + " "
elif current_mode in ["정방향", "역방향"] and current_sub:
result[current_mode][current_sub] += text + " "
상태 흐름:
공통 (초기)
↓ ("1. 정방향" 발견)
정방향
↓ ("2. 역방향" 발견)
역방향
8️⃣ HTTP 응답 객체
resp = requests.get(url)
print(resp) # <Response [200]>
print(resp.status_code) # 200
print(resp.headers) # {'Content-Type': 'text/html', ...}
print(resp.text) # <html><head>...</head><body>...</body></html>
속성내용
| resp.status_code | HTTP 상태 코드 (200=성공, 404=없음, 500=오류) |
|---|---|
| resp.headers | 응답 헤더 정보 |
| resp.text | HTML 문자열 |
| resp.content | 바이너리 데이터 (이미지 등) |
9️⃣ BeautifulSoup 파서 종류
# html.parser (파이썬 내장)
soup = BeautifulSoup(html, 'html.parser') # 의존성 없음, 느림
# lxml (외부 설치)
soup = BeautifulSoup(html, 'lxml') # 빠름
# html5lib (외부 설치)
soup = BeautifulSoup(html, 'html5lib') # 가장 관대함
🔟 속성 접근
item = soup.select_one('a')
# 텍스트 내용
item.get_text() # "타로카드 1번"
# HTML 속성 (대괄호로 접근)
item['href'] # "/post1"
item['class'] # ["post-item"] (리스트)
메서드 요약 테이블
메서드/속성역할반환
| select() | CSS 선택자로 모든 요소 찾기 | 리스트 |
|---|---|---|
| select_one() | CSS 선택자로 첫 요소만 찾기 | 단일 요소 |
| find_all() | 특정 태그들 모두 찾기 | 리스트 |
| get_text() | 텍스트만 추출 | 문자열 |
| prettify() | 들여쓰기된 HTML 출력 | 문자열 |
| ['속성명'] | HTML 속성 접근 | 속성값 |
반응형