[크롤링] 이미지 크롤링

html 문서에서 img 태그와 같은 태그들은 src 라는 속성을 가지고 있다.


해당 src 속성의 주소로 이동하면, 해당 이미지의 원본이 나타나게 된다

이미지 크롤링에는 두 가지 라이브러리를 사용할 것이다.


1
2
import os #파일 시스템을 위한 라이브러리 ex) 파일, 폴더 생성, 삭제, 존재 여부 파악
from urllib.request import urlretrieve as urlre #이미지 경로를 파일로 저장
cs

1. 이미지를 저장할 파일의 조작
2. img 태그의 src를 이용하여 저장할 수 있도록 지원하는 라이브러리


img 태그 src 추출

img 태그의 src의 추출은 다음 예제와 같이 수행이 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from selenium import webdriver as wb
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as bs
import time
import os #파일 시스템을 위한 라이브러리 ex) 파일, 폴더 생성, 삭제, 존재 여부 파악
from urllib.request import urlretrieve as urlre #이미지 경로를 파일로 저장
 
url = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query=%EB%B3%84'
driver = wb.Chrome()
driver.get(url)
 
#해당 사이트의 모든 img 태그 
soup = bs(driver.page_source,'lxml')
img = soup.select('img._image._listImage')
 
img_list=[]
#img 태그 src 전체 추출
for i in img :
    img_list.append(i['src'])
img_list
cs


추출된 img 태그['속성']
-해당 속성에 대한 값의 추출


폴더 생성

os.mkir('파일 경로/파일의 이름')
-> 이때 이미 있는 파일의 경우 오류가 발생한다.

os.mkdir('파일 경로/파일의 이름')
-> 파일이 있는 경우 True 값 반환

파일 생성 예제 - 파이썬 실행 중인 현재 폴더와 이웃함
1
2
3
4
5
6
import os 
if not os.path.isdir('./이미지') :
    os.mkdir('./이미지')
    print('폴더 생성')
else :
    print(0)
cs



해당 페이지의 모든 이미지 수집



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
33
34
35
36
from selenium import webdriver as wb
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as bs
import time
import os #파일 시스템을 위한 라이브러리 ex) 파일, 폴더 생성, 삭제, 존재 여부 파악
from urllib.request import urlretrieve as urlre #이미지 경로를 파일로 저장
 
if not os.path.isdir('./이미지') :
    os.mkdir('./이미지')
    print('폴더 생성')
else :
    print('이미 있는 폴더')
 
url = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=image&query=%EB%B1%81%EC%83%88&oquery=%EB%B3%84&tqi=hoKc8wp0YidssCmX5XGssssss%2F8-216352'
drive = wb.Chrome()
drive.get(url)
 
#맨 아래로 스크롤
for i in range(50) :
    driver.find_element_by_css_selector('body').send_keys(Keys.PAGE_DOWN)
    time.sleep(0.3)
 
#
soup = bs(driver.page_source,'lxml')
img = soup.select('img._image._listImage')
 
#두가지 유형의 이미지 수집-> 아래 설명 참조
img_list=[]
for i in img :
    try :
        img_list.append(i['data-lazy-src'])
    except :
        img_list.append(i['src'])
 
for i in range(len(img_list)) :
    urlre(img_list[i],'./이미지/{}.jpg'.format(i))
cs

네이버 이미지의 경우

일반적인 img 태그의 src는 이미지로 연결되는 url 이지만, 일부는 다음과 같은 형식을 갖는다

data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 

대신 data-lazy-src 속성에 이미지로 연결되는 url 을 갖는다

댓글