Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 자바
- 자바암호
- GPT-4's answer
- spring integration
- 소프트웨어공학
- write by chatGPT
- flet
- 리눅스
- JVM
- 인프라
- 시스템
- jpa
- Database
- chatGPT's answer
- python
- NIO
- 자바네트워크
- Java
- 유닉스
- write by GPT-4
- 데이터베이스
- 고전역학
- oracle
- spring data jpa
- 파이썬
- 역학
- 코틀린
- kotlin
- android
- 웹 크롤링
Archives
- Today
- Total
기억을 지배하는 기록
학습사이트 http://quotes.toscrape.com/ BFS 크롤링 본문
Web Crawling for Beginners
학습사이트 http://quotes.toscrape.com/ BFS 크롤링
Andrew's Akashic Records 2024. 4. 24. 13:59728x90
http://quotes.toscrape.com/
사이트를 너비 우선 탐색(BFS) 방법으로 크롤링하고, 크롤링된 데이터를 엑셀 파일에 저장하는 파이썬 스크립트를 작성해드리겠습니다. 이 스크립트는 각 페이지에서 인용구, 저자, 태그를 추출하고, 설정된 최대 깊이(max_depth
)까지 탐색합니다.
필요한 라이브러리 설치
다음 라이브러리를 설치하세요. requests
와 BeautifulSoup
는 웹 크롤링을 위해, pandas
와 openpyxl
은 엑셀 파일 작업을 위해 사용됩니다.
pip install beautifulsoup4 requests pandas openpyxl
너비 우선 탐색(BFS) 웹 크롤러 코드
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from collections import deque
import pandas as pd
def extract_quotes(soup):
"""페이지에서 인용구, 저자, 태그를 추출합니다."""
quotes_data = []
quotes = soup.find_all('div', class_='quote')
for quote in quotes:
text = quote.find('span', class_='text').text
author = quote.find('small', class_='author').text
tags = [tag.text for tag in quote.find_all('a', class_='tag')]
quotes_data.append({'text': text, 'author': author, 'tags': ', '.join(tags)})
return quotes_data
def bfs_crawl(start_url, max_depth=3):
"""너비 우선 탐색(BFS)으로 사이트를 크롤링합니다."""
queue = deque([(start_url, 0)])
visited = set()
all_quotes = []
while queue:
current_url, depth = queue.popleft()
if depth > max_depth:
continue
if current_url in visited:
continue
visited.add(current_url)
response = requests.get(current_url)
soup = BeautifulSoup(response.text, 'html.parser')
all_quotes.extend(extract_quotes(soup))
# 다음 페이지 링크 찾기
next_button = soup.find('li', class_='next')
if next_button:
next_url = next_button.find('a')['href']
next_page_url = urljoin(current_url, next_url)
queue.append((next_page_url, depth + 1))
return all_quotes
# 크롤링 시작
start_url = 'http://quotes.toscrape.com/'
quotes = bfs_crawl(start_url, max_depth=2)
# 결과를 DataFrame으로 변환 후 Excel 파일로 저장
df = pd.DataFrame(quotes)
df.to_excel('quotes.xlsx', index=False, engine='openpyxl')
print("Crawling completed and data saved to Excel.")
코드 설명
- 함수
extract_quotes
:- BeautifulSoup 객체를 받아 해당 페이지에서 인용구, 저자, 태그를 추출합니다.
- 각 인용구 정보를 리스트로 반환합니다.
- 함수
bfs_crawl
:- 시작 URL에서부터 크롤링을 시작하여, 너비 우선 탐색 방식으로 모든 페이지를 방문합니다.
- 각 페이지마다
extract_quotes
함수를 호출하여 인용구 정보를 수집합니다. - 'Next' 버튼을 찾아 다음 페이지의 URL을 큐에 추가하며, 최대 깊이(
max_depth
)까지 탐색합니다.
- 엑셀 파일 저장:
- 수집된 모든 인용구 데이터를 pandas DataFrame으로 변환합니다.
- DataFrame을 'quotes.xlsx' 파일로 저장합니다. 파일 작업에
openpyxl
엔진을 사용합니다.
이 스크립트는 지정된 깊이까지 http://quotes.toscrape.com/
사이트의 모든 페이지를 방문하고 인용구 정보를 엑셀 파일로 저장합니다. 설정된 깊이는 크롤링을 멈출 지점을 결정합니다.
728x90
'Web Crawling for Beginners' 카테고리의 다른 글
Python 사용자 인증 (JWT) 받기 (0) | 2024.04.25 |
---|---|
Python 사용자 인증 (Session) 받기 (0) | 2024.04.25 |
학습사이트 http://books.toscrape.com BFS 크롤링 (0) | 2024.04.24 |
URL 깊이 우선 탐색(DFS) 웹 크롤러 (0) | 2024.04.24 |
URL 너비 우선 탐색(BFS) 웹 크롤러 (0) | 2024.04.24 |
Comments