!pip install bs4
Collecting bs4 Requirement already satisfied: beautifulsoup4 in c:\anaconda3\lib\site-packages (from bs4) (4.6.0) Installing collected packages: bs4 Successfully installed bs4-0.0.1
import bs4
import os
os.chdir(r"C:\Users\Gram\Desktop\myPyCode\02 데이터 수집과 처리 - 실습\data")
#컴퓨터에 저장된 html파일로 parshing하기위해 파일 읽어오기
f = open("page_02b.html","r")
my_html = f.read()
f.close()
# 3 가지 parser 중 'html.parser' 선택
soup = bs4.BeautifulSoup(my_html, 'html.parser') #res.text가 텍스트(문자열), BeautifulSoup4로 파싱해 soup객체로 변환시킴
#soup객체 생성
print(soup.prettify()) #soup객체에서 prettify메서드 사용(조금 더 읽기 쉬운 형태로 출력위해)
<!DOCTYPE HTML> <html lang="“en”"> <!-- 이 행은 주석. --> <head> <meta content="text/html; charset=utf-8"/> <title> CSS 셀렉터 예문 2 </title> </head> <!-- 여기까지가 헤드. --> <!-- style 정의! --> <style> .myClass1 { color:blue; background-color:gray; font-weight:bolder; } .myClass2 { color:red; background-color:yellow; font-weight:lighter; } .myClass3 { color:green; background-color:orange; font-weight:normal; } div.myClass3 { color:white; background-color:black; font-weight:normal; } li.myClass3 { color:gray; background-color:red; font-weight:bolder; } #myID1 { color:yellow; background-color:violet; font-weight:bolder; } #myID2 { color:yellow; background-color:blue; font-weight:bolder; } </style> <body> <h1 class="myClass1"> 헤더 1.1 </h1> <h1 class="myClass2"> 헤더 1.2 </h1> <h1 class="myClass3"> 헤더 1.3 </h1> <h2 class="myClass1"> 헤더 1.1 </h2> <h2 class="myClass2"> 헤더 1.2 </h2> <h2 class="myClass3"> 헤더 1.3 </h2> <p class="myClass1"> Paragraph 1. </p> <p class="myClass2" id="myID1"> Paragraph 2. </p> <p class="myClass3"> Paragraph 3. </p> <div class="myClass3"> <br/> <span> A Single line within a div tag. </span> <br/> <p class="myClass1"> Paragraph 4. </p> <p class="myClass2"> Paragraph 5. </p> <p class="myClass3"> Paragraph 6. </p> <br/> </div> <br/> <div> <br/> 다음은 ordered list이다: <ol> <li class="myClass1"> 아이템 하나. </li> <li class="myClass2"> 아이템 둘. </li> <li class="myClass3" id="myID2"> 아이템 셋. </li> <li class="myClass1"> 아이템 넷. </li> <li class="myClass2"> 아이템 다섯. </li> <li class="myClass3"> 아이템 여섯. </li> </ol> <br/> </div> </body> <!-- 여기까지가 몸통. --> </html>
# 첫 번째 <p> 태그를 찾아서 출력한다.
x=soup.find('p') #첫번째 p태그를 가져옴
print(x.text.strip()) #p태그 텍스트에서 strip
Paragraph 1.
# 모든 <p> 태그의 내용을 찾아서 이어 붙여 출력한다.
x=soup.find_all('p') #모든 p태그 가져오기 #x는 리스트성격
n = len(x) #길이로 x의 원소개수 확인
result = '' #빈 문자열 만들어 원소 하나하나 가져옴 # 초기화.
#x[i]태그객체를 가져와 text속성가져옴
for i in range(n):
result += x[i].text.strip() + '\n\n' #문자열 메서드 strip(왼쪽 오른쪽 스페이스 떨궈줌)
#\n\n(라인 체인지), +(두개 연결)
# 출력.
print(result) #p태그 안에 있는 내용만 나옴
Paragraph 1. Paragraph 2. Paragraph 3. Paragraph 4. Paragraph 5. Paragraph 6.
type(x) #결과값 ResultSet은 리스트형태로 나옴: 인덱싱해서 원소 가져올 수 있음
type(x[0]) #첫번째 원소 가져옴
for i in range(n):
result += x[i].text.strip() #인덱싱해 원소가져옴
# 모든 <div> 태그의 내용을 찾아서 이어 붙여서 출력한다.
x=soup.find_all('div') #모든 p태그 가져오기 #x는 리스트성격
n = len(x) #길이로 x의 원소개수 확인
result = '' #빈 문자열 만들어 원소 하나하나 가져옴 # 초기화.
#x[i]태그객체를 가져와 text속성가져옴
for i in range(n):
result += x[i].text.strip() + '\n\n' #문자열 메서드 strip(왼쪽 오른쪽 스페이스 떨궈줌)
#\n\n(라인 체인지), +(두개 연결)
# 출력.
print(result)
A Single line within a div tag. Paragraph 4. Paragraph 5. Paragraph 6. 다음은 ordered list이다: 아이템 하나. 아이템 둘. 아이템 셋. 아이템 넷. 아이템 다섯. 아이템 여섯.
# 첫 번째 <ol> 태그를 찾아서 출력해 본다.
x=soup.find('ol')
print(x.text) # 첫 ol태그의 text 속성 #내용 보여줌, 하위태그 포함, 문자열 타입
아이템 하나. 아이템 둘. 아이템 셋. 아이템 넷. 아이템 다섯. 아이템 여섯.
res = soup.find_all(class_='myClass1') #myClass1이라는 클래스를 갖는 태그들만 가져온다
for x in res:
print(x) #클래스는 같지만 서로다른 태그들을 가져온게 보임
<h1 class="myClass1"> 헤더 1.1 </h1> <h2 class="myClass1"> 헤더 1.1 </h2> <p class="myClass1"> Paragraph 1. </p> <p class="myClass1"> Paragraph 4. </p> <li class="myClass1"> 아이템 하나. </li> <li class="myClass1"> 아이템 넷. </li>
print(x.text)
아이템 넷.
res = soup.find_all(class_='myClass2')
for x in res:
print(x.text) #지저분한 태그떼고 내용들만 보여줌
헤더 1.2 헤더 1.2 Paragraph 2. Paragraph 5. 아이템 둘. 아이템 다섯.
res = soup.find_all('p',class_='myClass2') #p태그면서 myClass2인거만
for x in res:
print(x.text) #p태그이면서 myClass2인 결과는 2가지
Paragraph 2. Paragraph 5.
print(x)
<p class="myClass2"> Paragraph 5. </p>
res = soup.find_all('li',class_='myClass3') #li태그면서 myClass3인거만
for x in res:
print(x.text)
아이템 셋. 아이템 여섯.
print(x)
<li class="myClass3"> 아이템 여섯. </li>
res = soup.find(id='myID1')
print(res.text)
Paragraph 2.
res = soup.find(id='myID2')
print(res.text)
아이템 셋.