basic/python

python 05 [실습02] - find_all(), select() 함수 사용하여 원하는 태그 찾기

못지(Motji) 2021. 8. 24. 23:27
import하고 파싱하기
from bs4 import BeautifulSoup
html = '''<html>
<head><title>test title</title></head>
<body><p id="a"> hello1 </p><p class="a"> hello2 </p><p class="b"> hello3 </p></body>
</html>'''
soup = BeautifulSoup(html, 'lxml')​

 

find() : 원하는 태그 하나를 얻을 수 있다.

find_all() 원하는 태그들을 리스트 형태로 얻을 수 있다.

❕ 태그명으로 가져오기

print(soup.find_all('title'))
print(soup.find_all('p'))

🖥️ console 출력

 

 

❕ id값으로 가져오기

print(soup.find_all(id='a'))
print(soup.find_all(id=True)) # 아이디 속성이 있는것들 가져오기
#False는 id 속성값이 없는것 전부 가져옴

🖥️ console 출력

 

❕ 태그명, id로 가져오기

print(soup.find_all('p',id='a'))
print(soup.find_all('p',id='c')) # 없는요소면 빈 리스트 return

🖥️ console 출력

 

❕ 태그명, class로 가져오기

print(soup.find_all('p', class_='a'))
print(soup.find_all('p', class_='b'))

🖥️ console 출력

 

❕ 텍스트

print(soup.find_all('p', text=' hello1 '))

🖥️ console 출력

 

❕ 검색양 제한주기

print(soup.find_all('p', limit=1))
print(soup.find_all(['p', 'title'])) #태그 여러개 같이 가져오기

🖥️ console 출력

 

❕ 두번 걸러서 가져오기

body = soup.find_all('body')
p = body[0].find_all('p')
print(p)
print(p[0])

🖥️ console 출력

 

❕ find() 함수로 요소 한개 가져오기

print(soup.find('p', class_='b'))

🖥️ console 출력

 


import하고 파싱하기
html = '''<html>
<head>
    <title class="a">test title</title>
</head>
<body>
    <p id="i" class="a">hahaha1</p>
    <p class="b">hahaha2</p>
    <p class="c">hahaha3</p>
    <a href="/ex/test01">a tag</a>
    <b>b tag</b>
</body>
</html>'''
soup = BeautifulSoup(html, 'lxml')

 

❕ select() : CSS 선책자를 이용해 원하는 요소 리스트로 받기

print(soup.select('p')) # 태그명
print(soup.select('.a')) # .클래스속성값
print(soup.select('.b'))
print(soup.select('p#i')) # p태그인데 아이디값이 i인것

🖥️ console 출력