BeautifulSoup

BeautifulSoup


BeautifulSoup 설치

pip install beautifulsoup4

네이버 영화 데이터 수집


# 모듈 import
import requests

# 요청
url = 'https://movie.naver.com/movie/sdb/rank/rmovie.naver'
params = { 'sel':'cnt','date':'20221005' }
response = requests.get(url, params=params)

# 성공 시 응답 데이터 저장
if response.status_code == 200:
    print(response.url)
    data = response.text

BeautifulSoup 객체로 변환


# 모듈 import
from bs4 import BeautifulSoup

# str => BeautifulSoup 객체
soup = BeautifulSoup(data)
print(type(soup))

태그 사용 데이터 추출


soup.태그명

# 존재 태그
title = soup.title
print(title)
print(title.string, title.text, title.get_text())

# 비 존재 태그
title = soup.title1
print(title) # None

soup('태그명')

# 존재 태그
meta= soup('meta')
print(meta)

# 비 존재 태그
meta= soup.meta1
print(meta) # [] 빈객체

soup.태그명.attrs['속성명']

# 존재 태그
meta= soup('meta').attrs['content']
print(meta)

# 비 존재 태그 확인 후 처리
if soup.meta.has_attr('content'):
    print(soup.meta.attrs['content'])

find(), find_all() 사용 해서 추출


# 존재 태그
title = soup.find('title')
print(title)

# 비 존재 태그
title = soup.find('title1')
print(title) # None

# 존재 태그
meta = soup.find_all('meta')
print(meta)

# 비 존재 태그
meta = soup.find_all('meta1')
print(meta) # [] 빈 객체

네이버 영화 리스트 영역 선택


영화 리스트 전체

table_count = len(soup.find_all('table')) # 1개
#table = soup.find_all('table'))[0] # [0] 선택 필요
movie_table = soup.find('table') # 1개 이므로 find() 추출

영화 제목 추출 : 영화 제목 1개 영역 확인

html

<div class="tit3">
<a href="/movie/bi/mi/basic.naver?code=210852" title="정직한 후보2">정직한 후보2</a>
</div>

python

print(movie_table.find(class_='tit3'))

영화 제목 추출 : 영화 제목 모든 영역

movie_items = movie_table.find_all(class_='tit3')
print(len(movie_items))

영화 제목 리스트에 저장

movie_items = movie_table.find_all(class_='tit3')

# title 1개 추출
title = movie_table.find_all(class_='tit3')[0].a.text
print(title)

# title 모두 추출
title_list = []
for i in movie_items:
    title = i.a.get_text()
    title_list.append(title)
print(len(title_list))

영화 code값 리스트에 저장

movie_items = movie_table.find_all(class_='tit3')

# code 1개 추출
code = movie_items[0].a.attrs['href'].split('=')[1]
print(code)

# code 모두 추출
code_list = []
for i in movie_items:
    code = i.a.attrs['href'].split('=')[1]
    code_list.append(code)
print(len(code_list))

영화 code:title 딕셔너리로 합치기

movie_info = dict(list(zip(code_list,title_list)))

select_one(), select() 사용 해서 추출


# 존재 태그
title = soup.select_one('title')
print(title)

# 비 존재 태그
title = soup.select_one('title1')
print(title) # None

# 존재 태그
meta = soup.select('meta')
print(meta)

# 비 존재 태그
meta = soup.select('meta1')
print(meta) # [] 빈 객체

네이버 영화 리스트 영역 선택


영화 리스트 전체

table_count = len(soup.select('table')) # 1개
#table = soup.select('table'))[0] # [0] 선택 필요
movie_table = soup.select_one('table') # 1개 이므로 find() 추출

영화 제목 추출 : 영화 제목 1개 영역 확인

html

<div class="tit3">
<a href="/movie/bi/mi/basic.naver?code=210852" title="정직한 후보2">정직한 후보2</a>
</div>

python

print(movie_table.select_one('.tit3'))

영화 제목 추출 : 영화 제목 모든 영역

movie_items = movie_table.select('.tit3')
print(len(movie_items))

영화 제목 리스트에 저장

movie_items = movie_table.select('.tit3')

# title 1개 추출
title = movie_table.select('.tit3')[0].a.text
print(title)

# title 모두 추출
title_list = []
for i in movie_items:
    title = i.a.get_text()
    title_list.append(title)
print(len(title_list))

영화 code값 리스트에 저장

movie_items = movie_table.select('.tit3')

# code 1개 추출
code = movie_items[0].a.attrs['href'].split('=')[1]
print(code)

# code 모두 추출
code_list = []
for i in movie_items:
    code = i.a.attrs['href'].split('=')[1]
    code_list.append(code)
print(len(code_list))

영화 code:title 딕셔너리로 합치기

movie_info = dict(list(zip(code_list,title_list)))

연습