본문 바로가기

Python_Intermediate/JupyterNotebook

190224> Jupyter Notebook으로 확인하는 BeautifulSoup

반응형
In [32]:
#-*- coding: utf-8 -*-
from bs4 import BeautifulSoup as bs
In [33]:
html_doc = """
<table border=1> 
  <tr>     
     <th id = "choco">초콜릿</th>    
     <th id = "cookie">과자</th>  
  </tr>  
  <tr>    
     <td name = "candy">사탕</td>
     <td>오렌지</td>
  </tr>  
</table>
"""
In [34]:
# html 파서를 이용해서 html 형태의 데이터를 읽어온다.
soup = bs(html_doc, 'html.parser')
In [35]:
# 1. td 태그를 모두 찾아서 td_list 담은 후, 루프를 돌리면서 각 td 태그 내용을 출력한다.
td_list = soup.find_all('td')
In [36]:
for td_item in td_list:
  print(td_item.string)
사탕
오렌지
In [37]:
# 2. id 가 choco 인 항목을 찾아서 해당 태그 내용을 출력한다.
# html style로 찾는 방법
id_list = soup.find(id='choco')
print(id_list.string)
초콜릿
In [38]:
id_list = soup.find(id='cookie')
print(id_list.string)
과자
In [39]:
td_list = soup.find('td', {'name':'candy'})
print(td_list.find_next_sibling().string)
오렌지
In [40]:
# css style로 찾는 방법
td_list = soup.select('#choco')
print(td_list[0].string)
초콜릿
In [41]:
td_list = soup.select('td[name="candy"]')
print(td_list[0].find_next_sibling().string)
오렌지
< BeautifulSoup 기초 확인 방법 >


반응형

'Python_Intermediate > JupyterNotebook' 카테고리의 다른 글

Magic Commands  (0) 2019.03.01