★검색엔진이 내 사이트를 퍼가는 행위를 크롤링이라고 하고

★스크랩핑은 신문 스크랩하듯이 사이트 데이터를 스크랩하는걸 뜻함

★대부분 혼용 크롤링이라 부름

 

스크랩핑이 가능한 이유가 웹사이트 데이터를 이미 받아서 브라우저에 표현을 하고있는 상태이기 때문에

내가 보는 화면의 데이터를 솎아낼수가 있음

 

 

크롤링을 할때 중요한 두가지

 

첫번쨰 

코드 단에서 브라우저를 켜지 않고 요청을 하는것

(requests) 요청하는것

 

두번째 

브라우저-검사 를 눌러 많은 html중에 내가 원하는 정보를 잘 솎아내는것

(bs4)

 

결론 requests로 용청하고 beautifulsoup으로 솎아 낸다

1
2
3
4
5
6
7
8
9
import requests
from bs4 import BeautifulSoup
 
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
 
soup = BeautifulSoup(data.text, 'html.parser')
 
 
cs

※headers={...} 붙이는 이유는 코드단에서 요청을 할때 이런 기본적인 요청은 막아둔 사이트가 많아서 내가 엔터 친것과 같은 효과를 내줌

 

beautifulsoup의 사용방법은 크게 select 와 select_one으로 나뉨

1.select_one

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
from bs4 import BeautifulSoup
 
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
 
soup = BeautifulSoup(data.text, 'html.parser')
 
 
 
title = soup.select_one('#old_content > table > tbody > tr:nth-child(2) > td.title > div > a')
 
print(title)
cs

※브라우저에서 가져오는법

오른쪽 클릭 →copy→copy selecter

//그린북 html ===== #old_content > table > tbody > tr:nth-child(2) > td.title > div > a//int(

 

※텍스트를 가져오고싶으면 

print(title.text)

속성을 가져오고싶으면

print(title['href'])

 

2.select

하나가 아닌 여러개를 가져오고싶을때 두개의 코드를 비교해보고 중복되는 코드를 가지고 오면 전부다 해당이 된다

중복되는 부분인 #old~tr 이면 모든 차트 해당됌

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
from bs4 import BeautifulSoup
 
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
 
soup = BeautifulSoup(data.text, 'html.parser')
 
trs = soup.selct('##old_content > table > tbody > tr')
 
for tr in trs:
    print(tr)
 
cs

tr들이 다 나옴

 

이 tr들 안에서 title들을 찾는 법

위에 비교해서 코드를 찾은것 처럼

copy select 한후 비교해보면 td~a 가 나옴

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
from bs4 import BeautifulSoup
 
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
 
soup = BeautifulSoup(data.text, 'html.parser')
 
trs = soup.selct('#old_content > table > tbody > tr')
 
for tr in trs:
    a_tag = tr.select_one('td.title > div > a')
    print(a_tag)
cs

run 을 하면 중간중간에 none이라고 나오는데 사이트마다 다 다르기 때문에 각각 사이트마다 전략을 가져가야함

보면 차트 중간중간 줄든인데 이걸 결과값에서 안나오게하려면 아래처럼 명령하면 됌

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests
from bs4 import BeautifulSoup
 
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
 
soup = BeautifulSoup(data.text, 'html.parser')
 
trs = soup.selct('#old_content > table > tbody > tr')
 
for tr in trs:
    a_tag = tr.select_one('td.title > div > a')
    if a_tag is not none:
        title = a_tag.text
        print(title)
cs

 

 

 

순위, 제목, 평점 가져오기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import requests
from bs4 import BeautifulSoup
 
# URL을 읽어서 HTML를 받아오고,
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
 
# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
soup = BeautifulSoup(data.text, 'html.parser')
 
# select를 이용해서, tr들을 불러오기
movies = soup.select('#old_content > table > tbody > tr')
 
# movies (tr들) 의 반복문을 돌리기
for movie in movies:
    # movie 안에 a 가 있으면,
    a_tag = movie.select_one('td.title > div > a')
    if a_tag is not None:
        rank = movie.select_one('td:nth-child(1) > img')['alt'# img 태그의 alt 속성값을 가져오기
        title = a_tag.text                                      # a 태그 사이의 텍스트를 가져오기
        star = movie.select_one('td.point').text                # td 태그 사이의 텍스트를 가져오기
        print(rank,title,star)
cs

 

※크롤링은 정답이 없고 사람마다 방식이 다 다르기 때문에 결과만 뽑아내면 됌

+ Recent posts