Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 파이썬
- pandas
- level 1
- 데이터 분석
- 빅분기
- Python
- 카카오
- 튜닝
- 오라클
- 코딩테스트
- 알고리즘
- 프로그래머스
- sklearn
- seaborn
- oracle
- 빅데이터 분석 기사
- SQL
- matplotlib
- 실습
- level 2
- 머신러닝
- Kaggle
- python3
- Oracel
- R
- 실기
- Numpy
Archives
- Today
- Total
라일락 꽃이 피는 날
[Python] BeautifulSoup 본문
728x90
BeautifulSoup
from bs4 import BeautifulSoup
html = '''
<html>
<head>
<title>BeautifulSoup test</title>
</head>
<body>
<div id='upper' class='test' custom='good'>
<h3 title='Good Content Title'>Contents Title</h3>
<p>Test contents</p>
</div>
<div id='lower' class='test' custom='nice'>
<p>Test Test Test 1</p>
<p>Test Test Test 2</p>
<p>Test Test Test 3</p>
</div>
</body>
</html>'''
soup = BeautifulSoup(html)
1. find
검색 조건을 명시하여 tag를 검색한다.
soup.find('h3')
soup.find('div', class_='test')
attrs = {'id': 'upper', 'class': 'test'}
soup.find('div', attrs=attrs)
2. find_all
조건에 맞는 모든 tag를 리스트로 반환한다.
soup.find_all('p')
soup.find_all(re.compile('h\d'))
3. get_text
조건에 맞는 tag 안의 value를 추출한다.
부모 tag의 경우, 모든 자식 tag의 value를 추출한다.
tag = soup.find('h3')
tag.get_text()
tag = soup.find('div', id='upper')
tag.get_text().strip()
4. attribute 값 추출
검색한 tag에 attribute 이름을 [ ]연산을 통해 추출한다.
tag = soup.find('h3')
tag['title']
5. select, select_one
- 태그명 찾기 tag
- 자손 태그 찾기 - 자손 관계 (tag tag)
- 자식 태그 찾기 - 다이렉트 자식 관계 (tag > tag)
- 아이디 찾기 #id
- 클래스 찾기 .class
- n번째 자식 tag 찾기 :nth-child(n)
soup.select('h3')
soup.select('#harmonyContainer p')
soup.select('#harmonyContainer > p')
soup.select('.tit_view')
soup.select('span.txt_info:nth-child(1)')
- 속성값 찾기 [name='test']
- 속성값 prefix 찾기 [name ^='test']
- 속성값 suffix 찾기 [name $='test']
- 속성값 substring 찾기 [name *='test]
soup.select('h3[class="tit_view"]')
soup.select('h3[class^="txt"]')
soup.select('h3[class$="view"]')
soup.select('h3[class*="view"]')
728x90
'프로그래밍 > Python' 카테고리의 다른 글
[Python] ASCII (아스키 코드) (0) | 2021.10.11 |
---|---|
[Python] selenium (0) | 2021.08.22 |
[Python] Open API (0) | 2021.08.22 |
[Python] requests (0) | 2021.08.22 |
[Python] 정규 표현식 (regular expression) 2 (0) | 2021.08.16 |