기계는 거짓말하지 않는다

Python BeautifulSoup 사용법, 속성 본문

Python

Python BeautifulSoup 사용법, 속성

KillinTime 2021. 7. 20. 20:20

설치

Linux

apt-get install python-bs4 (파이썬 2의 경우)

apt-get install python3-bs4 (파이썬 3의 경우)

 

Other

easy_install beautifulsoup4

pip install beautifulsoup4

pip install bs4

파서 설치

lxml

설정에 따라 다음 명령 중 하나로 lxml을 설치

 

apt-get install python-lxml

easy_install lxml

pip install lxml

 

html5lib

HTML을 구문 분석 하는 순수 Python html5lib 파서. 설정에 따라 다음 명령 중 하나로 html5lib를 설치

 

apt-get install python-html5lib

easy_install html5lib

pip install html5lib

간단한 일반적인 사용 방법

from bs4 import BeautifulSoup

# html 소스를 가져와야 함
soup = BeautifulSoup(html)

# title 태그를 가져옴
soup.title

# title 태그의 태그 이름을 가져옴
soup.title.name

# title 태그의 내용을 가져옴
soup.title.string

# title 태그의 상위 태그 이름을 가져옴
soup.title.parent.name

# p 태그를 가져옴
soup.p

# p 태그의 "string" 속성의 값을 가져옴 class, id 등
soup.p['string']

# a 태그를 가져옴
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

# 모든 a 태그를 가져옴 [<a>~</a>, <a>~</a>]
soup.find_all('a')

# id1인 태그를 가져옴
soup.find(id="id1")

# a 태그의 text를 가져옴
soup.a.text

# b 태그의 이름 = b
tag = soup.b
tag.name # b

속성

tag = BeautifulSoup('<b id="boldest">bold</b>', 'html.parser').b
tag['id'] # 'boldest'

tag.attrs # {'id': 'boldest'}

태그를 모두 갖고와서 하나씩 얻기

for link in soup.find_all('a'):
    print(link.get('href'))

모든 텍스트 추출

print(soup.get_text())

#   <p class="title">
#    <b>
#     Title
#    </b>
#   </p>
#   <p class="text">
#    This location is textbox.
#   </p>

# 결과
# Title
#
# This location is textbox.

문자열 확인, 변경

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>', 'html.parser')
tag = soup.b
tag.string # 'Extremely bold'
type(tag.string) # <class 'bs4.element.NavigableString'>

# unicode string
unicode_string = str(tag.string)
unicode_string # 'Extremely bold'
type(unicode_string) # <type 'str'>

# replace
tag.string.replace_with("No longer bold")
tag # <b class="boldest">No longer bold</b>

CSS 클래스

Link: CSS Selector 연습

css_soup = BeautifulSoup('<p class="body strikeout"></p>', 'html.parser')
css_soup.find_all("p", class_="strikeout") # [<p class="body strikeout"></p>]

css_soup.find_all("p", class_="body") # [<p class="body strikeout"></p>]

# 둘 이상의 클래스와 일치하는 태그 검색.
# CSS Selector
css_soup.select("p.strikeout.body") # [<p class="body strikeout"></p>]

 

출처: Beautiful Soup 문서

 

Beautiful Soup Documentation — Beautiful Soup 4.9.0 documentation

Non-pretty printing If you just want a string, with no fancy formatting, you can call str() on a BeautifulSoup object (unicode() in Python 2), or on a Tag within it: str(soup) # ' I linked to example.com ' str(soup.a) # ' I linked to example.com ' The str(

www.crummy.com

 

'Python' 카테고리의 다른 글

Python Selenium WebDriver 사용법, 메서드  (0) 2021.07.24
Python Matplotlib 폰트 확인, 적용  (0) 2021.07.23
Python Selenium, BeautifulSoup  (0) 2021.07.19
Python Crawling  (0) 2021.07.19
Python OpenCV (4) 이미지 편집  (0) 2021.07.14
Comments