먼저 cmd에서 beautifulsoop을 설치해야 한다. 설치 경로를 아래와 같이 바꿔준다.
아래 명령어를 실행한다.
이제이클립스 pedev에서 아래와 같이 코딩한다.
import bs4
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>
Page title
</title>
</head>
<body>
<p id="firstpara" align="center">
This is paragraph
<b>
one
</b>
.
</p>
<p id="secondpara" align="blah">
This is paragraph
<b>
two
</b>
.
</p>
</body>
</html>
"""
soup = BeautifulSoup( html_doc, 'html.parser' )
#print( soup.prettify() );
print( soup.title ) #타이틀만 출력
print( soup.title.name ) #타이틀의 벨류값
print( soup.title.string )
print( soup.title.parent ) #타이틀태그를 감싸고 있는 부모태크
<title>
Page title
</title>
title
Page title
<head>
<title>
Page title
</title>
</head>
이번엔 class가 있는 p태그를 출력해보자. 이때 가장 먼저나오는 것을 가져온다.
import bs4
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>
Page title
</title>
</head>
<body>
<p id="firstpara" align="center" class="stroy">
This is story
<b>
one
</b>
.
</p>
<p id="secondpara" align="blah" class="title">
This is title
<b>
two
</b>
.
</p>
</body>
</html>
"""
soup = BeautifulSoup( html_doc, 'html.parser' )
print( soup.p['class'] )
find_all() 사용 이번에는 모든 p태그를 찾아보자 이때 list_p 는 리스트 타입으로 저장된다.
import bs4
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>
Page title
</title>
</head>
<body>
<p id="firstpara" align="center" class="stroy">
This is story
<b>
one
</b>
.
</p>
<p id="secondpara" align="blah" class="title">
This is title
<b>
two
</b>
.
</p>
</body>
</html>
"""
soup = BeautifulSoup( html_doc, 'html.parser' )
list_p = soup.find_all( 'p' )
print( list_p )
print( type( list_p ) ) #리스트타입으로 저장된다.
print( list_p[0] )
print( list_p[1] )
[<p align="center" class="stroy" id="firstpara">
This is story
<b>
one
</b>
.
</p>, <p align="blah" class="title" id="secondpara">
This is title
<b>
two
</b>
.
</p>]
<class 'bs4.element.ResultSet'>
<p align="center" class="stroy" id="firstpara">
This is story
<b>
one
</b>
.
</p>
<p align="blah" class="title" id="secondpara">
This is title
<b>
two
</b>
.
</p>
클래스나 id값을 통해서 가져오기
이때 클래스는 class_ = '클래스명' 을 사용한다.
import bs4
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>
Page title
</title>
</head>
<body>
<p id="firstpara" align="center" class="stroy">
This is story
<b>
one
</b>
.
</p>
<p id="secondpara" align="blah" class="title">
This is title
<b>
two
</b>
.
</p>
</body>
</html>
"""
soup = BeautifulSoup( html_doc, 'html.parser' )
#ID 값으로 검색
print( soup.find_all( id='secondpara' ))
#class로 검색 1
print( soup.find_all( 'p', { 'class': 'title'} ) )
#class로 검색 2
print( soup.find_all( class_='title' ) )
[<p align="blah" class="title" id="secondpara">
This is title
<b>
two
</b>
.
</p>]
[<p align="blah" class="title" id="secondpara">
This is title
<b>
two
</b>
.
</p>]
[<p align="blah" class="title" id="secondpara">
This is title
<b>
two
</b>
.
</p>]
보통 find와 find_all을 주로 많이 사용한다.
찾는 태그를 제한하기 limit=제한횟수 를 이용한다.
import bs4
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>
Page title
</title>
</head>
<body>
<p id="firstpara" align="center" class="stroy">
This is story
<b>
one
</b>
.
</p>
<p id="secondpara" align="blah" class="title">
This is title
<b>
two
</b>
.
</p>
<p id="secondpara" align="blah" class="content">
This is content
<b>
two
</b>
.
</p>
</body>
</html>
"""
soup = BeautifulSoup( html_doc, 'html.parser' )
#p 태그 2개까지만 찾기
print( soup.find_all( 'p', limit=2 ) )
[<p align="center" class="stroy" id="firstpara">
This is story
<b>
one
</b>
.
</p>, <p align="blah" class="title" id="secondpara">
This is title
<b>
two
</b>
.
</p>]
실습) 다음 페이지의 뉴스 제목 크롤링하기
import bs4
import requests
from bs4 import BeautifulSoup
html_url = 'https://daum.net/'
html_doc = requests.get( html_url ).text
soup = BeautifulSoup( html_doc, 'html.parser' )
titles = soup.find_all( class_='tit_item' )
for title in titles:
print( title.text )
'국회는 공직자 목에 방울을 메달라!' [TF사...
중대본 "수도권 통제해야 3차 유행 재확산 억제...
산수유·홍매화 만개한 대전 한밭수목원[픽! 대전...
성탄 이브에 세상에 왔다 성탄에 떠난 화가
"우리 엄마 코로나 백신 맞으러"..노모 안고...
역주행 화물차, 핸들 돌려 인명피해 막았다[영상...
귀여움 주의! 쏘대장 운동시켰다가
내 남자의 차에서 발견한 수상한 흔적
카메라 울렁증 있는 자신의 모습에...
연 매출 170억이었던 이곳 현재 상황
찐 권력의 상징 = 초고층 빌딩?! 부자가 초고층에...
(정동원 or 임영웅) 일편단심 서원이의 사랑 고민...
(FULL) 쏘대장님과 함께하는 철원 라이프.. 힐...
일 안 하는 알코올 의존증 아빠 때문에 꿈을 포기했...
서하준, 홍수아 스캔들로 도발하는 진미령에 '착잡'
"철저히 짓밟을 거야" 홍석, 서하준에 복수 선전포...
이다희 - Your Eyes(Acoustic ver...
'스카이캐슬, 완벽한 타인' 레전드 작품에 이어 예...
뜻밖의 애국 포마드
곱빼기 시켰는데 양이 너무 많아서.jpg
'먹방 열풍'? 이곳, 전혀 다른 세상
따뜻한 날씨가 반갑지 않은 건...
독을 마시면서까지 시도했던 것
당신에게 '녹색'을 처방합니다
"휴지만 사도 손이 벌벌 떨려요..."
그럼에도, 전화주문은 있어야 합니다
하루 평균 7개나 필요하다는데...
이 청년들이 주말을 반납하고 하는 일