[python] 파이썬 BeautifulSoup으로 이미지 추출하기
파이썬의 BeautifulSoup 라이브러리를 사용하면 웹 페이지에서 이미지를 추출할 수 있습니다. BeautifulSoup은 HTML과 XML 문서를 파싱하고 태그 구조를 다루는 데 사용됩니다.
필요한 라이브러리 설치
먼저, BeautifulSoup을 사용하기 위해 파이썬 패키지 매니저 pip을 사용하여 라이브러리를 설치해야 합니다. 터미널 또는 명령 프롬프트에서 다음 명령어를 실행합니다:
pip install beautifulsoup4
코드 예시
아래는 파이썬으로 BeautifulSoup을 사용하여 이미지를 추출하는 간단한 예시 코드입니다.
from bs4 import BeautifulSoup
import requests
# 웹 페이지의 URL
url = 'https://example.com'
# GET 요청을 보내고 응답을 받음
response = requests.get(url)
# 응답의 HTML 내용을 BeautifulSoup으로 파싱
soup = BeautifulSoup(response.content, 'html.parser')
# 모든 이미지 태그를 찾음
image_tags = soup.find_all('img')
# 이미지 URL을 추출하여 출력
for image_tag in image_tags:
image_url = image_tag['src']
print(image_url)
위 코드는 example.com 웹 페이지에서 모든 이미지 태그를 찾아서 그 URL을 출력합니다.
참고 자료
- BeautifulSoup 공식 문서: https://www.crummy.com/software/BeautifulSoup/bs4/doc/