basic/python

python 05 [실습01] 파싱하기, 태그접근하기

못지(Motji) 2021. 8. 24. 23:13

 

html 코드

html = '''<html>
<head><title class="t a b" id="tid">test title</title></head>
<body><p> hello1 </p><p> hello2 </p><p> hello3 </p></body>
</html>'''

❕ 파싱

soup = BeautifulSoup(html, 'lxml') # html, 파서 던져주어 파싱하기, 문자열을 html로 변환시킴
print(soup.prettify()) # html 구조에 맞게 예쁘게 출력됨
print(type(soup))

🖥️ console 출력

 

태그 접근하기

❕ 태그명으로 접근하기

.태그명 : 첫번째로 등장하는 태그 정보만 가져오기

title_tag = soup.title
print(title_tag)
print(type(title_tag))
print(title_tag.text) # 내용물만 뽑아오기
print(title_tag.string) # 그 태그안에 있는 내용물만 가져오기
print(title_tag.name) # 태그명 가져오기

🖥️ console 출력

 

❕ 태그 속성에 접근

print(title_tag['class']) # 클래스 속성은 여러개 지정이 가능하기 때문에 리스트로 return 해줌
print(title_tag['id'])
# print(title_tag['name']) # 리터럴 방식으로 없는것을 찾을시 error 발생
print(title_tag.get('name','해당 속성은 존재하지 않습니다')) # 없는것을 찾을시 None, 에러메세지 추가도 가능 (메소드사용)

🖥️ console 출력

 


html_ch 코드

html_ch = '''<html><head><title id="tid">test title</title></head>
<body><p><span>hahaha1</span><span>hahaha2</span></p></body></html>'''
soup = BeautifulSoup(html_ch, 'lxml') #파싱

❕ 자식태그 접근 : contents, children

p_children = soup.p.children
print(p_children)
for child in p_children:
    print(child)

p_cont = soup.p.contents
print(p_cont) # 리스트로 return

🖥️ console 출력

 

❕ 부모태그 접근 : parent, parents (최상위 부모가지 가져옴)

span = soup.span
print(span)
span_parent = span.parents
print(span_parent)

🖥️ console 출력

 

❕ 형재태그 접근 : next_sibling(뒤형제), previous_sibling(앞형제)

span = soup.span
a = span.next_sibling
print(a)
b = a.previous_sibling
print(b)

💻 웹문서 출력



html_ch 코드

html_ch = '''<html><head><title id="tid">test title</title></head>
<body>
    <p>
        <a>test1</a>
        <b>test2</b>
        <c>test3</c>
    </p>
</body></html>'''
soup = BeautifulSoup(html_ch, 'lxml') # 파싱

❕ 이전, 다음요소 접근 : next_element, previous_element (s 복수)

a = soup.a
b = soup.b
c = soup.c
print(a)
print(b)
print(c)
a_next = a.next_elements
print(a_next)
for a in a_next:
    print(a)

💻 웹문서 출력