from bs4 import BeautifulSoup
<html><head><title>MangoTitle</title></head>
<p class="title">Mango</p>
<p class="story">Once upon a time there were three little sisters;
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
# Beautifulsoup 객체를 생성한다.
soup = BeautifulSoup(html_doc,'lxml')
# .태그 이름으로 하위 태그로의 접근이 가능하다.
print("soup.body.p의 결과 : ", soup.body.p)
# 객체의 태그 속성은 파이썬 딕셔너리처럼 태그['속성 이름']으로 접근이 가능하다.
print("soup.a['href']의 결과 : ", soup.a['href'])
print("soup.title.name의 결과 : ", soup.title.name)
## string 변수 (참고) NavigableString: 문자열은 태그 안의 텍스트에 상응한다. BeautifulSoup은이런 텍스트를 포함하는 NavigableString 클래스를 사용한다.
print("soup.title.string의 결과 : ", soup.title.string)
print("soup.contents의 결과 : ", soup.contents)
find(name, attrs, recursive, string, **kwargs)
※ (주의) class는 파이썬 예약어이므로, class_를 사용한다.
print("soup.find()의 결과 : ", soup.find('a', attrs={'class' : 'sister'}))
# find_all() : 해당 태그가 여러 개 있을 경우 한꺼번에 모두 가져온다. 그 객체들의 리스트로 반환한다.
find_all(name, attrs, recursive, string, limit, **kwargs)
Limit –몇 개까지 찾을 것인가? find_all()로 검색했을 때, 수천, 수만 개가 된다면 시간이 오래 걸릴 것이다.
이때 몇 개까지만 찾을 수 있도록 제한을 둘 수 있는 인자다.
print("soup.find_all()의 결과 : ", soup.find_all('a', limit=2))