본문 바로가기

언어/python&웹 크롤링

[python&웹 크롤링] 10. BeautifulSoup 사용 및 웹 파싱 기초(2)

 

이전시간에 살펴봤던 BeautifulSoup을 활용한 웹 파싱 연습을 진행하겠다.

본인의 section2 폴더에 다음 html을 미리 저장시키자

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<body>
<div id="foods">
  <h1>안주 및 주류</h1>
  <ul id="fd-list">
    <li class="food hot" data-lo="ko">닭도리탕</li>
    <li class="food" data-lo="jp">돈까스</li>
    <li class="food hot" data-lo="ko">삼겹살</li>
    <li class="food" data-lo="us">스테이크</li>
  </ul>
  <ul id="ac-list">
    <li class="alcohol" data-lo="ko">소주</li>
    <li class="alcohol" data-lo="us">맥주</li>
    <li class="alcohol" data-lo="ko">막걸리</li>
    <li class="alcohol high" data-lo="cn">양주</li>
    <li class="alcohol" data-lo="ko">동동주</li>
  </ul>
</div>
<body>
</html>
 
cs

 food-list.html

 

1
2
3
4
5
6
7
8
<ul id="cars">
  <li id="ge">Genesis</li>
  <li id="av">Avante</li>
  <li id="so">Sonata</li>
  <li id="gr">Grandeur</li>
  <li id="tu">Tucson</li>
</ul>
 
cs

cars.html

 

두 파일은 파싱에 사용 될 html 문서들이다.

두 파일을 저장했으면, 다음 파일을 생성하여 코드를 입력하고, 실행 결과를 확인해보자.

정규표현식, 태그 선택자, css 선택자 등 활용하여 여러 방식으로 html 코드의 원하는 부분을 가져올 수 있다.

 

 

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
from bs4 import BeautifulSoup
import sys
import io
import re #regex re는 정규표현식 http://pythonstudy.xyz/python/article/401-정규-표현식-Regex
 
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
 
html = """
<html><body>
    <ul>
        <li><a id="naver" href="http://www.naver.com">naver</a></li>
        <li><a href="http://www.daum.net">daum</a></li>
        <li><a href="http://www.daum.co.kr">daum</a></li>
        <li><a href="https://www.google.com">google</a></li>
        <li><a href="https://www.tistory.com">tistory</a></li>
    </ul>
</body></html>
"""
 
soup = BeautifulSoup(html, 'html.parser')
print(soup.find(id="naver").string)
li = soup.find_all(href=re.compile(r"^https://www")) # compile안에 정규표현식 패턴 해당문자로 시작
 
 
for e in li :
    print(e.attrs['href'])
 
cs

download2-6-1.py

 

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
#선택자 활용해서 가져오기 ()
 
from bs4 import BeautifulSoup
import sys
import io
 
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
 
fp = open("food-list.html", encoding="utf-8")
soup = BeautifulSoup(fp, "html.parser")
 
print("1", soup.select("li:nth-of-type(4)")[1].string) #각 li 태그 그룹의 4번째 요소 선택
print("2", soup.select_one("#ac-list > li:nth-of-type(4)").string)
print("3", soup.select("#ac-list > li[data-lo='cn']")[0].string)
print("4", soup.select("#ac-list > li.alcohol.high")[0].string)
 
param = {"data-lo""cn""class""alcohol"}
print("5", soup.find("li", param).string)
print("6", soup.find(id="ac-list").find("li", param).string)
 
for ac in soup.find_all("li") :
    if ac['data-lo'== 'us':
        print('data-lo == us', ac.string)
 
cs

download2-6-2.py

 

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
32
 
from bs4 import BeautifulSoup
import sys
import io
 
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
 
fp = open("cars.html", encoding="utf-8")
soup = BeautifulSoup(fp, "html.parser")
 
def car_func(selector) :
    print("car_func", soup.select_one(selector).string)
 
 
car_func("#gr")
car_func("li#gr")
car_func("ul > li#gr")
car_func("#cars #gr")
car_func("#cars > #gr")
car_func("li[id='gr']")
 
car_lambda("#gr")
car_lambda("li#gr")
car_lambda("ul > li#gr")
car_lambda("#cars #gr")
car_lambda("#cars > #gr")
car_lambda("li[id='gr']")
 
print("car_func", soup.select("li")[3].string)
print("car_func", soup.find_all("li")[3].string)
 
cs

download2-6-3.py

 

코드를 입력하고 결과를 확인해보자.

download2-6-2.py, download2-6-3.py 에서 cars.html, food-list.html 을 이용해 파싱을 진행했다.

이전에 했던 내용들을 실습 한 것이기 때문에 따로 설명은 안하겠다.


Today :
Yesterday :
Total :