Creative Code

BeautifulSoup으로 html파싱 본문

코딩 study/python

BeautifulSoup으로 html파싱

빛하루 2023. 10. 26. 09:18
from bs4 import BeautifulSoup
import requests
import os
from urllib import request

# HTML 문서 예시
html_doc = """<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

# BeautifulSoup으로 HTML 파싱
soup = BeautifulSoup(html_doc, 'html.parser')

# 'soup' 객체를 사용하여 HTML 문서를 파싱하고 원하는 정보를 추출합니다.
print(soup)  # 파싱된 HTML 전체 문서 출력
print(soup.title)  # <title> 태그 내용 출력
print(soup.a)  # 첫 번째 <a> 태그 내용 출력
print(soup.title.string)  # <title> 태그 내용 중 텍스트 출력
print(soup.a['id'])  # 첫 번째 <a> 태그의 'id' 속성 값 출력
print(soup.find_all('a'))  # 모든 <a> 태그를 리스트로 출력
print(soup.find_all('p', 'story'))  # 'p' 태그 중 'class'가 'story'인 것들을 리스트로 출력
print(soup.find_all(id='link2'))  # 'id'가 'link2'인 태그를 리스트로 출력
print(soup.find_all(class_='sister'))  # 'class'가 'sister'인 태그를 리스트로 출력
# soup.css.select('title')  # 이 부분은 오류가 발생할 수 있으므로 주석 처리

# Google 이미지 검색 URL
url = 'https://www.google.com/search?q=%EA%B0%80%EC%9D%84&tbm=isch&ved=2ahUKEwi7_KjIvoGCAxXOyTQHHRsLAGoQ2-cCegQIABAA&oq=%EA%B0%80%EC%9D%84&gs_lcp=CgNpbWcQAzIECCMQJzILCAAQgAQQsQMQgwEyCAgAELEDEIMBMggIABCxAxCDATILCAAQgAQQsQMQgwEyCAgAELEDEIMBMggIABCxAxCDATILCAAQgAQQsQMQgwEyCAgAELEDEIMBMggIABCxAxCDAToFCAAQgAQ6CAgAEIAEELEDOgcIIxDqAhAnUOsFWO8dYKQfaAJwAHgBgAHcAYgB0g2SAQUwLjkuMZgBAKABAaoBC2d3cy13aXotaW1nsAEKwAEB&sclient=img&ei=U80wZfuGKs6T0-kPm5aA0AY&bih=865&biw=786'
result = requests.get(url)

# 이미지 다운로드를 위한 폴더 생성
path = os.path.dirname(__file__) + '/down/'
if not os.path.exists(path):
    os.makedirs(path)

# Google 이미지 검색 결과 페이지 내용 출력
print(result.text)

# BeautifulSoup으로 HTML 파싱
soup = BeautifulSoup(result.text, 'html.parser')
imgdata = soup.find_all('img')

# 이미지 다운로드 및 출력
for i, item in enumerate(imgdata):
    try:
        request.urlretrieve(item['src'], path + 'img_' + str(i) + '.jpg')
        print(item['src'])
    except:
        pass