황규진 2024. 7. 9. 10:05

ID로 특정 요소 찾기 : find()

from bs4 import BeautifulSoup
html = """
<html>
<body>
    <h1 id = "title1">스크래핑이란</h1>
    <p id = "paragraph_1">첫 번째 문단 시작 - 끝</p>
    <p> 두 번째 문단 시작 - 끝 </p>
    <h1 id = "title2">인공지능이란?</h1>
    <p id = "paragraph_3">세 번쨰 문단 시작 - 끝</p>
    <p> 네 번째 문단 시작 - 끝</p>
</body>
</html>
"""
soup = BeautifulSoup(html, 'html.parser')

title_1 = soup.find(id = 'title1')
print(title_1.text)
print(title_1.string)

스크래핑이란 스크래핑이란

result = soup.find(id = 'paragraph_3')
result.text

세 번쨰 문단 시작 - 끝

 

CLASS로 특정 요소 찾기 : find()

find('tag', {'class':'name'})
soup = BeautifulSoup(html, 'html.parser')

ul_class_greet = soup.find('ul', {'class':'greet'})
print(ul_class_greet)

<ul class="greet"> <li>hello</li> <li>bye</li> <li>welcome</li> </ul>

li_tags = ul_class_greet.findAll('li')
li_tags

[<li>hello</li>, <li>bye</li>, <li>welcome</li>]