BS4... find() , find_all()
페이지 정보
작성자 서방님 댓글 0건 조회 77회 작성일 20-07-29 09:28본문
>>> html = '''
<html>
<head> ........ '''
>>> from bs4 import BeautifulSoup
>>> bs = BeautifulSoup ( html , "html.parser" )
>>> print ( bs .perttify () ) # bs로 불러온 내용 보기
<html>
<head> .......
find, find_all
>>> bs . find ( 'title' ) # 태그값을 기준으로 내용 불러오기 (최초 검색 결과만 출력)
<title> test.web </title>
>>> bs. find_all ( 'p' ) # 해당 모든 태그를 불러온다 / [ 리스트 ]
[<p align.......> ......
>>> bs. find_all ( align = "center" ) # 속성값을 기준으로 태그를 불러온다
[ <p align = "center" .....
>>> bs. find_all ( 'p' , limit = 2 ) # 해당 모든 태그 중 2개 까지만
[<p align.......> ......
find(''). find('')
>>> head_tag = bs . find ( 'head' )
>>> head_tag . find ( 'title' ) # head 태그 내부 title 태그의 내용을 불러온다
>>> bs . find ( 'p' , align = "right" ) # p 태그 중 /and/ align = "right" 을 포함한 태그를 불러온다
<p align="right....... >
>>> body_tag = bs . find ( 'body' )
>>> list1 = body_tag. find_all ( ['p','img'] ) # [] 리스트 , 'p' /or/ 'img' 를 포함하는 태그를 불러온다
>>> for tag in list1 :
print ( tag )
< p align....
< img height = "300" ......>
정규식 함수 활용
>>> import re
>>> bs. find_all ( re . compile ("^p") ) # p 글자를 포함하는 태그
>>> bs. find_all ( text = " text contents 1" ) # text contents 1 을 포함하는 태그
>>> bs. find_all ( text = re . compile (" text + ") ) # text 부가 내용 포함하는 태그
>>> bs. find_all ( re . compile ("^p") ) # p라는 글자를 포함하는 태그를 불러온다.
문장으로 가져오기
>>> tags = bs .find ('body') .find_all ('img')
>>> tags . string # string 은 1번에 1문자 씩만 변환가능
' img = 'cowboy.jpg' '
>>> strings = tags . string
>>> for string in strings :
print (string)
>>> body_tag = bs.find('body')
>>> body_tag. get_text() # 모든 문자열을 하나의 문자열로 되돌린다.
' \n text contents1 \n text contents 2 \n tex...... '
>>> body_tag. get_text ( strip = True ) # \n 줄바꿈 기호가 삭제된 채 출력
' text contents1 text contents 2 tex...... '
>>> body_tag. get_text ( '-' , strip = True ) # \n 기호가 '- 로 출력
' text contents1 - text contents 2 - tex...... '
댓글목록
등록된 댓글이 없습니다.