Toy project

네이버 영화 웹 크롤링 + DB 구축 프로젝트(1) - crawling

땅지원 2022. 5. 31. 12:04

BeautifulSoup

request.text를 이용해 가져온 데이터는 텍스트형태의 html

텍스트형태의 데이터에서 원하는 html 태그를 추출하는데 도와주는 것이 BeautifulSoup

 

import requests
from bs4 import BeautifulSoup

url = 'https://kin.naver.com/search/list.nhn?query=%ED%8C%8C%EC%9D%B4%EC%8D%AC'

response = requests.get(url)

if response.status_code == 200:
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    print(soup)

else : 
    print(response.status_code)

응답 코드가 200 일때, html 을 받아와 soup 객체로 변환 한다

 

 Css 선택자를 자동으로 찾아주는 기능

import requests
from bs4 import BeautifulSoup

url = 'https://kin.naver.com/search/list.nhn?query=%ED%8C%8C%EC%9D%B4%EC%8D%AC'

response = requests.get(url)

if response.status_code == 200:
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    title = soup.select_one('#s_content > div.section > ul > li:nth-child(1) > dl > dt > a')
    print(title)
else : 
    print(response.status_code)

select_one : 하나의 html 요소를 찾는 함수인데, css 선택자를 사용해서 찾을 수 있다.

<a class="_nclicks:kin.txt _searchListTitleAnchor" href="https://kin.naver.com/qna/detail.nhn?d1id=8&
amp;dirId=80101&amp;docId=362502659&amp;qb=7YyM7J207I2s&amp;enc=utf8§ion=kin&
amp;rank=1&amp;search_sort=0&amp;spq=0" target="_blank">
<b>파이썬</b>배우기 쉬운곳 찾아요!!</a>

텍스트만 뽑아오고 싶다면 get_text() 함수를 이용하면 된다

print(title.get_text())

 

* 정규표현식 라이브러리 re를 이용해서 특수문자를 제거 할 수 있음

import re

# 특수문자 제거 위한 함수
def cleanText(readData):
    # 텍스트에 포함되어 있는 특수 문자 제거
    text = re.sub('[-=+#/\?:^$.@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`\'…》\r\t\n ]', '', readData)
    return text

<div>, <span>,<p> 등등 여러 태그 밑에 자식 태그들이 있을 수 있는데 우리가 찾는 정보가 자식태그에 있는 여러 정보들이라면 부모 태그에 있는 곳을 탐색한 후 필터링을 해줄 필요가 있다.

 

지금까지 알아본 것은 부모 태그를 get_text() 한 후 억지로 특수문자를 제거해서 결과물을 얻었지만

이번에는 부모태그 -> 자식태그 에서 하나씩 탐색을 하면서 추출을 해보려고 한다.

 

import requests

from bs4 import BeautifulSoup

url = 'https://movie.naver.com/movie/bi/mi/basic.naver?code=192608'

response = requests.get(url)

if response.status_code == 200:
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')

    kind = soup.select_one('#content > div.article > div.mv_info_area > div.mv_info > dl > dd:nth-child(2) > p > span:nth-child(1)')
    print(kind)
    res = kind.select('a')
    print(res)
    for char in res:
        print(char.get_text())

else :
    print(response.status_code)

부모태그의 kind에서 kind.select('a')를 통해 자식 태그에서 <a>태그에 있는것들만 따로 select를 해준것이고

그 태그들 안에서 get_text()를 한 모습이다.