!pip install bs4
Collecting bs4 Using cached https://files.pythonhosted.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz Requirement already satisfied: beautifulsoup4 in c:\anaconda3\lib\site-packages (from bs4) (4.6.0) Building wheels for collected packages: bs4 Building wheel for bs4 (setup.py): started Building wheel for bs4 (setup.py): finished with status 'done' Created wheel for bs4: filename=bs4-0.0.1-cp37-none-any.whl size=1278 sha256=06533789adfb36bb318ff649b1ad9aed2b9f3152c808e448126b8f38fe9bcedf Stored in directory: C:\Users\Gram\AppData\Local\pip\Cache\wheels\a0\b0\b2\4f80b9456b87abedbc0bf2d52235414c3467d8889be38dd472 Successfully built bs4 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_01b.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> 이 것은 타이틀 태그 내용이다! </title> </head> <!-- 여기까지가 헤드. --> <body> <h1> 헤더 1 </h1> <h2> 헤더 2 </h2> <h3> 헤더 3 </h3> <h4> 헤더 4 </h4> <h5> 헤더 5 </h5> <p> 데이터 분석에 대해서 배워 봅시다. </p> <p> 이제 span 태그로 <span style="color:Red;"> 색을 바꾸어 </span> 봅시다. </p> <div> 다음은 unordered list 이다: <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> </div> <div> 다음은 ordered list이다: <ol> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ol> </div> <div> 다음은 ordered list인데 색상을 넣어 본다: <ol> <li> <span style="color:Red;"> 아이템 하나. </span> </li> <li> <span style="color:Blue;"> 아이템 둘. </span> </li> <li> <span style="color:Green;"> 아이템 셋. </span> </li> <li> <span style="color:Orange;"> 아이템 넷. </span> </li> <li> <span style="color:Violet;"> 아이템 다섯. </span> </li> </ol> </div> <p> 이 것은 <a href="http://www.naver.com"> 네이버 </a> 로 가는 하이퍼링크이다. <br/> <br/> 이 것은 <a href=".\page_01a.html"> 로컬 파일 </a> 로 가는 하이퍼링크이다. <br/> <br/> 폰트를 <em> 한번 바꾸어 </em> 보도록 한다: 이 것은 <strong> 볼드 </strong> 폰트이고, 이 것은 <b> 볼드 </b> 폰트이며, 이 것은 <i> 이탤릭 </i> 폰트이고, 또한 이 것은 <u> 밑줄친 </u> 폰트이다. </p> <div> 이제는 아래와 같이 테이블을 만들어 보도록 한다. <br/> <br/> <table> <thead> <tr> <th> Column 1 </th> <th> Column 2 </th> <th> Column 3 </th> </tr> </thead> <tr> <td> (1,1) </td> <td> (1,2) </td> <td> (1,3) </td> </tr> <tr> <td> (2,1) </td> <td> (2,2) </td> <td> (2,3) </td> </tr> </table> </div> <div> <br/> <br/> 그리고, 다음 이미지도 출력해 본다. <br/> <figure> <img alt="Figure not found in this folder!!!" height="200" src=".\fig_01.png" width="250"/> <br/> <figurecaption> 위는 막대그래프를 모여주는 그림. </figurecaption> </figure> </div> <div> <br/> 마지막으로 <span style="color:Blue;"> input </span> 태그와 <span style="color:Blue;"> button </span> 태그, <span style="color:Blue;"> select </span> 태그를 만들어 본다. <br/> <br/> <input type="text" value="test1"/> <input type="text" value="test2"/> <input type="text" value="test3"/> <button> Button 1 </button> <button> Button 2 </button> <button> Button 3 </button> <br/> <br/> <select> <option value="선택_1"> 선택_1 </option> <option value="선택_2"> 선택_2 </option> <option value="선택_3"> 선택_3 </option> <option value="선택_4"> 선택_4 </option> </select> <br/> <br/> 끝~~ <br/> <br/> </div> </body> <!-- 여기까지가 몸통. --> </html>
print(soup.title) # 첫 title 태그 전체 나옴
print(soup.title.text) # 첫 title 태그의 text 속성 #내용 보여줌, 하위태그 포함, 문자열 타입
<title>이 것은 타이틀 태그 내용이다!</title> 이 것은 타이틀 태그 내용이다!
print(soup.p) # 첫 p 태그 전체 나옴
print(soup.p.text) # 첫 p 태그의 text 속성 #내용 보여줌, 하위태그 포함, 문자열 타입
print(soup.p.string) # 첫 p 태그의 string 속성 #내용 보여줌, 하위태그 미포함 #하위객체가 없어 위랑 같은 결과
print(soup.p.contents) # 첫 p 태그의 contents 속성 #리스트형태로 자식태그 가져옴
<p> 데이터 분석에 대해서 배워 봅시다. </p> 데이터 분석에 대해서 배워 봅시다. 데이터 분석에 대해서 배워 봅시다. [' 데이터 분석에 대해서 배워 봅시다. ']
print(soup.p.attrs) # 첫 p 태그의 attrs. #속성과 해당값을 딕셔너리로 변환
#print(soup.p.attrs['class']) => 이렇게 하면 클래스라는 키가 없어서 아무것도 안나옴
print(soup.p.get('class')) # 첫 p 태그의 class. #class속성 값을 가져옴
print(soup.p.get('id')) # 첫 p 태그의 id. #id속성 값을 가져옴
#값이 없어서 아무것도 안나옴
{} None None
print(soup.span) # 첫 span 태그 전체.
print(soup.span.text) # 첫 span 태그의 text 속성. #내용 보여줌, 하위태그 포함, 문자열 타입
print(soup.span.string) # 첫 span 태그의 string 속성. #내용 보여줌, 하위태그 미포함
print(soup.span.contents) # 첫 span 태그의 contents 속성. #리스트형태로 자식태그 가져옴
<span style="color:Red;">색을 바꾸어</span> 색을 바꾸어 색을 바꾸어 ['색을 바꾸어']
print(soup.span.attrs) # 첫 span 태그의 attrs. #속성과 해당값을 딕셔너리로 변환
print(soup.span.get('class')) # 첫 span 태그의 class. #class속성 값을 가져옴
print(soup.span.get('id')) # 첫 span 태그의 id. #id속성 값을 가져옴
{'style': 'color:Red;'} None None
print(soup.span.get('style')) # 첫 span 태그의 style. #style속성 값을 가져옴
print(soup.span.attrs['style']) # 첫 span 태그의 style. #대괄호해도 위의 결과 같음
color:Red; color:Red;
my_div = soup.div # div 태그 객체. #.Tag라고 뜸
print(type(my_div)) # div 태그 객체의 type 출력.
print(my_div) # 첫 div 태그 전체출력
<class 'bs4.element.Tag'> <div> 다음은 unordered list 이다: <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> </div>
print(my_div.text) # 첫 div 태그의 text 속성. #내용 보여줌, 하위태그 포함, 문자열 타입
print(my_div.string) # 첫 div 태그의 string 속성. #div태그에 string속성이 없어 None나옴
다음은 unordered list 이다: 아이템 하나. 아이템 둘. 아이템 셋. 아이템 넷. 아이템 다섯. None
print(my_div.contents) # 첫 div 태그의 contents 속성. #리스트형태로 자식태그 가져옴
['\n다음은 unordered list 이다:\n', <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul>, '\n']
print(my_div.attrs) # 첫 div 태그의 attrs. #속성과 해당값을 딕셔너리로 변환
print(my_div.get('class')) # 첫 div 태그의 class. #class속성 값을 가져옴
print(my_div.get('id')) # 첫 div 태그의 id. #id속성 값을 가져옴
{} None None
my_img = soup.img # img 태그 객체.
print(type(my_img)) # img 태그 객체의 type 출력.
print(my_img.attrs) # 속성과 해당값을 딕셔너리로 변환
<class 'bs4.element.Tag'> {'src': '.\\fig_01.png', 'width': '250', 'height': '200', 'alt': 'Figure not found in this folder!!!'}
print(my_img.get('src')) #src속성 값을 가져옴
print(my_img.attrs['src']) #src속성 값을 가져옴 #대괄호해도 위의 결과 같음
.\fig_01.png .\fig_01.png
print(my_img.get('alt')) #src속성 값을 가져옴 #alt(대안텍스트)-이미지 못가져왔을 때 보여주는 대체문구
Figure not found in this folder!!!
my_a = soup.a # a 태그 객체.
print(my_a.attrs) # 속성과 해당값을 딕셔너리로 변환
{'href': 'http://www.naver.com'}
print(my_a.get('href')) #href속성 값을 가져옴
http://www.naver.com
my_div = soup.div # div 태그 객체.
my_div_children = my_div.children # div 태그의 자식 객체. #my_div=my_div_children임
n = 0
for x in my_div_children: # iterator 객체는 for 루프로 접근 => div_children 가지고 반복하겠다
print(str(n) + " : " + str(x.name)) # div_children을 for루프에 넣음 => 태그의 이름이 나옴
print("-"*30)
n += 1 #위에서 'Wn'이런게 이름없는데 div_children으로 잡혀서 none으로 나온듯
0 : None ------------------------------ 1 : ul ------------------------------ 2 : None ------------------------------
my_div_children = my_div.children # div 태그의 자식들. Iteration 하기 전 리셋.
my_div_children_list = [x for x in my_div_children] # iterator 객체를 list로 변환.
n = 0
for x in my_div_children_list: #iterator로 리스트만들거나, 리스트로 리스트 만들거나
print(str(n) + " : \n") #div_children에서 값을 하나 뽑아 만듬, \n으로 라인 체인지
#리스트만들어 또 iterator
print(x) #ul 나옴
print("-"*30)
n += 1
0 : 다음은 unordered list 이다: ------------------------------ 1 : <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> ------------------------------ 2 : ------------------------------
for문 설명
x=range(10) #이건 리스트 아님 = > 이터레이션 할수 있음
x
[y*2 for y in x] #x에서 y값 뽑아서 y*2를 리스트로 만들어라
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
x=range(10) #이건 리스트 아님
[y for y in x if y % 2 ==0] #2의 배수인경우 리스트를 마들어줘라
[0, 2, 4, 6, 8]
my_ul = soup.ul # ul 태그에 접근
my_ul_parents = my_ul.parents # ul 태그의 부모들. Iteration 하기 전 리셋.
n = 0
for x in my_ul_parents:
print(str(n) + " : " + x.name)
print("-"*30)
n += 1
0 : div ------------------------------ 1 : body ------------------------------ 2 : html ------------------------------ 3 : [document] ------------------------------
my_ul_parents = my_ul.parents # ul 태그의 부모들. Iteration 하기 전 리셋.
my_ul_parents_list = [x for x in my_ul_parents] #리스트화 함
n = 0
for x in my_ul_parents_list:
print(str(n) + " : \n")
print(x)
print("-"*30)
n += 1 #위의위에 것까지 나오니 결국 다 나온 것(상위의 상위)
0 : <div> 다음은 unordered list 이다: <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> </div> ------------------------------ 1 : <body> <h1> 헤더 1 </h1> <h2> 헤더 2 </h2> <h3> 헤더 3 </h3> <h4> 헤더 4 </h4> <h5> 헤더 5 </h5> <p> 데이터 분석에 대해서 배워 봅시다. </p> <p> 이제 span 태그로 <span style="color:Red;">색을 바꾸어</span> 봅시다. </p> <div> 다음은 unordered list 이다: <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> </div> <div> 다음은 ordered list이다: <ol> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ol> </div> <div> 다음은 ordered list인데 색상을 넣어 본다: <ol> <li> <span style="color:Red;">아이템 하나.</span> </li> <li> <span style="color:Blue;">아이템 둘. </span> </li> <li> <span style="color:Green;">아이템 셋. </span> </li> <li> <span style="color:Orange;">아이템 넷. </span> </li> <li> <span style="color:Violet;">아이템 다섯. </span> </li> </ol> </div> <p> 이 것은 <a href="http://www.naver.com"> 네이버</a>로 가는 하이퍼링크이다. <br/> <br/> 이 것은 <a href=".\page_01a.html"> 로컬 파일</a>로 가는 하이퍼링크이다. <br/> <br/> 폰트를 <em> 한번 바꾸어 </em> 보도록 한다: 이 것은 <strong> 볼드 </strong> 폰트이고, 이 것은 <b> 볼드 </b> 폰트이며, 이 것은 <i> 이탤릭 </i> 폰트이고, 또한 이 것은 <u>밑줄친</u> 폰트이다. </p> <div> 이제는 아래와 같이 테이블을 만들어 보도록 한다. <br/> <br/> <table> <thead> <tr> <th> Column 1 </th> <th> Column 2 </th> <th> Column 3 </th> </tr> </thead> <tr> <td> (1,1) </td> <td> (1,2) </td> <td> (1,3) </td> </tr> <tr> <td> (2,1) </td> <td> (2,2) </td> <td> (2,3) </td> </tr> </table> </div> <div> <br/> <br/> 그리고, 다음 이미지도 출력해 본다. <br/> <figure> <img alt="Figure not found in this folder!!!" height="200" src=".\fig_01.png" width="250"/> <br/> <figurecaption>위는 막대그래프를 모여주는 그림.</figurecaption> </figure> </div> <div> <br/> 마지막으로 <span style="color:Blue;">input</span> 태그와 <span style="color:Blue;">button</span> 태그, <span style="color:Blue;">select</span> 태그를 만들어 본다. <br/> <br/> <input type="text" value="test1"/> <input type="text" value="test2"/> <input type="text" value="test3"/> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <br/> <br/> <select> <option value="선택_1">선택_1</option> <option value="선택_2">선택_2</option> <option value="선택_3">선택_3</option> <option value="선택_4">선택_4</option> </select> <br/> <br/> 끝~~ <br/> <br/> </div> </body> ------------------------------ 2 : <html lang="“en”"> <!-- 이 행은 주석. --> <head> <meta content="text/html; charset=utf-8"/> <title>이 것은 타이틀 태그 내용이다!</title> </head> <!-- 여기까지가 헤드. --> <body> <h1> 헤더 1 </h1> <h2> 헤더 2 </h2> <h3> 헤더 3 </h3> <h4> 헤더 4 </h4> <h5> 헤더 5 </h5> <p> 데이터 분석에 대해서 배워 봅시다. </p> <p> 이제 span 태그로 <span style="color:Red;">색을 바꾸어</span> 봅시다. </p> <div> 다음은 unordered list 이다: <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> </div> <div> 다음은 ordered list이다: <ol> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ol> </div> <div> 다음은 ordered list인데 색상을 넣어 본다: <ol> <li> <span style="color:Red;">아이템 하나.</span> </li> <li> <span style="color:Blue;">아이템 둘. </span> </li> <li> <span style="color:Green;">아이템 셋. </span> </li> <li> <span style="color:Orange;">아이템 넷. </span> </li> <li> <span style="color:Violet;">아이템 다섯. </span> </li> </ol> </div> <p> 이 것은 <a href="http://www.naver.com"> 네이버</a>로 가는 하이퍼링크이다. <br/> <br/> 이 것은 <a href=".\page_01a.html"> 로컬 파일</a>로 가는 하이퍼링크이다. <br/> <br/> 폰트를 <em> 한번 바꾸어 </em> 보도록 한다: 이 것은 <strong> 볼드 </strong> 폰트이고, 이 것은 <b> 볼드 </b> 폰트이며, 이 것은 <i> 이탤릭 </i> 폰트이고, 또한 이 것은 <u>밑줄친</u> 폰트이다. </p> <div> 이제는 아래와 같이 테이블을 만들어 보도록 한다. <br/> <br/> <table> <thead> <tr> <th> Column 1 </th> <th> Column 2 </th> <th> Column 3 </th> </tr> </thead> <tr> <td> (1,1) </td> <td> (1,2) </td> <td> (1,3) </td> </tr> <tr> <td> (2,1) </td> <td> (2,2) </td> <td> (2,3) </td> </tr> </table> </div> <div> <br/> <br/> 그리고, 다음 이미지도 출력해 본다. <br/> <figure> <img alt="Figure not found in this folder!!!" height="200" src=".\fig_01.png" width="250"/> <br/> <figurecaption>위는 막대그래프를 모여주는 그림.</figurecaption> </figure> </div> <div> <br/> 마지막으로 <span style="color:Blue;">input</span> 태그와 <span style="color:Blue;">button</span> 태그, <span style="color:Blue;">select</span> 태그를 만들어 본다. <br/> <br/> <input type="text" value="test1"/> <input type="text" value="test2"/> <input type="text" value="test3"/> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <br/> <br/> <select> <option value="선택_1">선택_1</option> <option value="선택_2">선택_2</option> <option value="선택_3">선택_3</option> <option value="선택_4">선택_4</option> </select> <br/> <br/> 끝~~ <br/> <br/> </div> </body> <!-- 여기까지가 몸통. --> </html> ------------------------------ 3 : <!DOCTYPE HTML> <html lang="“en”"> <!-- 이 행은 주석. --> <head> <meta content="text/html; charset=utf-8"/> <title>이 것은 타이틀 태그 내용이다!</title> </head> <!-- 여기까지가 헤드. --> <body> <h1> 헤더 1 </h1> <h2> 헤더 2 </h2> <h3> 헤더 3 </h3> <h4> 헤더 4 </h4> <h5> 헤더 5 </h5> <p> 데이터 분석에 대해서 배워 봅시다. </p> <p> 이제 span 태그로 <span style="color:Red;">색을 바꾸어</span> 봅시다. </p> <div> 다음은 unordered list 이다: <ul> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ul> </div> <div> 다음은 ordered list이다: <ol> <li> 아이템 하나. </li> <li> 아이템 둘. </li> <li> 아이템 셋. </li> <li> 아이템 넷. </li> <li> 아이템 다섯. </li> </ol> </div> <div> 다음은 ordered list인데 색상을 넣어 본다: <ol> <li> <span style="color:Red;">아이템 하나.</span> </li> <li> <span style="color:Blue;">아이템 둘. </span> </li> <li> <span style="color:Green;">아이템 셋. </span> </li> <li> <span style="color:Orange;">아이템 넷. </span> </li> <li> <span style="color:Violet;">아이템 다섯. </span> </li> </ol> </div> <p> 이 것은 <a href="http://www.naver.com"> 네이버</a>로 가는 하이퍼링크이다. <br/> <br/> 이 것은 <a href=".\page_01a.html"> 로컬 파일</a>로 가는 하이퍼링크이다. <br/> <br/> 폰트를 <em> 한번 바꾸어 </em> 보도록 한다: 이 것은 <strong> 볼드 </strong> 폰트이고, 이 것은 <b> 볼드 </b> 폰트이며, 이 것은 <i> 이탤릭 </i> 폰트이고, 또한 이 것은 <u>밑줄친</u> 폰트이다. </p> <div> 이제는 아래와 같이 테이블을 만들어 보도록 한다. <br/> <br/> <table> <thead> <tr> <th> Column 1 </th> <th> Column 2 </th> <th> Column 3 </th> </tr> </thead> <tr> <td> (1,1) </td> <td> (1,2) </td> <td> (1,3) </td> </tr> <tr> <td> (2,1) </td> <td> (2,2) </td> <td> (2,3) </td> </tr> </table> </div> <div> <br/> <br/> 그리고, 다음 이미지도 출력해 본다. <br/> <figure> <img alt="Figure not found in this folder!!!" height="200" src=".\fig_01.png" width="250"/> <br/> <figurecaption>위는 막대그래프를 모여주는 그림.</figurecaption> </figure> </div> <div> <br/> 마지막으로 <span style="color:Blue;">input</span> 태그와 <span style="color:Blue;">button</span> 태그, <span style="color:Blue;">select</span> 태그를 만들어 본다. <br/> <br/> <input type="text" value="test1"/> <input type="text" value="test2"/> <input type="text" value="test3"/> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <br/> <br/> <select> <option value="선택_1">선택_1</option> <option value="선택_2">선택_2</option> <option value="선택_3">선택_3</option> <option value="선택_4">선택_4</option> </select> <br/> <br/> 끝~~ <br/> <br/> </div> </body> <!-- 여기까지가 몸통. --> </html> ------------------------------
my_li = soup.li # li 태그 객체.
my_li_siblings = my_li.next_siblings # li 태그 이후의 형제들(-s). Iteration 하기 전 리셋.
n = 0
for x in my_li_siblings: # iterator 객체는 for 루프로 접근.
print(str(n) + " : " + str(x.name)) #텍스트나 라인체인지가 텍스트로 잡혀서 none 나옴
print("-"*30)
n += 1
0 : None ------------------------------ 1 : li ------------------------------ 2 : None ------------------------------ 3 : li ------------------------------ 4 : None ------------------------------ 5 : li ------------------------------ 6 : None ------------------------------ 7 : li ------------------------------ 8 : None ------------------------------
my_li_siblings = my_li.next_siblings # li 태그 이후의 형제들. Iteration 하기 전 리셋.
my_li_siblings_list = [x for x in my_li_siblings]
n = 0
for x in my_li_siblings_list:
print(str(n) + " : \n") # 빈칸있는 이유는 '/n'라인체인지가 siblings로 잡혀서(결론은 깔끔하지 않음)
print(x) # 아이템원은 왜 siblings로 잡힘?
print("-"*30) # 아이템원 기준으로 next siblings가져오니 두개,세개 잡힘
0 : ------------------------------ 0 : <li> 아이템 둘. </li> ------------------------------ 0 : ------------------------------ 0 : <li> 아이템 셋. </li> ------------------------------ 0 : ------------------------------ 0 : <li> 아이템 넷. </li> ------------------------------ 0 : ------------------------------ 0 : <li> 아이템 다섯. </li> ------------------------------ 0 : ------------------------------