반응형
사용할 라이브 러리
from bs4 import BeautifulSoup
html생성
html_doc = """
<!doctype html>
<html>
<head>
<title> 기초 크롤링 </title>
</head>
<body>
크롤링을 해봅시다.
</body>
</html>
"""
해드 탐색
bs_obj = BeautifulSoup(html_doc, "html.parser")
head = bs_obj.find("head")
print(head)
바디 탐색
body = bs_obj.find("body")
print(body)
html 새로 지정
html_doc = """
<!doctype html>
<html>
<head>
기초 크롤링 따라하기
</head>
<body>
<div> 첫 번째 부분 </div>
<div> 두 번째 부분 </div>
</body>
</html>
"""
body부분 전체 출력
bs_obj = BeautifulSoup(html_doc, "html.parser")
body = bs_obj.find("body")
print(body)
div부분 추출 첫번째만 추출됨
div1 = bs_obj.find("div")
print(div1)
div부분 전체 추출
div_total = bs_obj.find_all("div")
print(div_total)
div 두번째 출하기
div2 = div_total[1]
print(div2)
print(div2.text)
속성 실습
html_doc = """
<!doctype html>
<html>
<head>
<title> 기초 크롤링 </title>
</head>
<body>
<table border="1">
<caption> 과일 가격 </caption>
<tr>
<th> 상품 </th>
<th> 가격 </th>
</tr>
<tr>
<td> 오렌지 </td>
<td> 100 </td>
<//tr>
<tr>
<td> 사과 </td>
<td> 150 </td>
</tr>
</table>
<table border="2">
<caption> 의류 가격 </caption>
<tr>
<th> 상품 </th>
<th> 가격 </th>
</tr>
<tr>
<td> 셔츠 </td>
<td> 30000 </td>
</tr>
<tr>
<td> 바지 </td>
<td> 50000 </td>
</tr>
</table>
</body>
</html>
"""
bs_obj = BeautifulSoup(html_doc, "html.parser")
clothes = bs_obj.find_all("table", {"border":"2"})
print(clothes)
반응형