ecsimsw

Google image crawler / Crawling / Scraping / python 본문

Google image crawler / Crawling / Scraping / python

JinHwan Kim 2019. 12. 1. 17:34

Google image crawler

 

   -  파이썬으로 크롤링을 공부하고 이를 연습해보기 위한 간단한 프로젝트로 구글 이미지 다운로더를 만들었다.

 

   - 구글에서 검색하고자 하는 이미지를, 미리 정의해둔 개수만큼 저장한다. 언어는 python, 라이브러리는 Urllib, BeautifulSoup4, Selenium을 주로 사용하였다.

 

Crawling / Scraping

 

https://ecsimsw.tistory.com/entry/Crawling-Scraping?category=869268

 

Crawling / Scraping / 구글 이미지 크롤러

1) urllib / BeautifulSoup - Beautiful Soup is a Python library for pulling data out of HTML and XML files. #example1 from bs4 import BeautifulSoup html ="""

jinhwan

web..

ecsimsw.tistory.com

 

1. 초기 변수 설정 

import sys, os
from bs4 import BeautifulSoup
from selenium import webdriver
import urllib, urllib.request
import requests
import random
import time
from selenium.webdriver.common.keys import Keys

###initial set

folder = ".image/"
url = "https://www.google.com/search"
webDriver = "./chromedriver.exe"
searchItem = "door"
size = 300

params ={
   "q":searchItem
   ,"tbm":"isch"
   ,"sa":"1"
   ,"source":"lnms&tbm=isch"
}

   - webDriver : 웹 드라이버 브라우저를 코드로 제어하여 동적인 웹 페이지의 정보를 가져올 수 있도록 한다. 이 코드에서는 웹 드라이버를 자동으로 페이지 다운하여, 한 html 소스에 더 많은 이미지를 담기 위해 사용한다.

 

2. 브라우저 구동

url = url+"?"+urllib.parse.urlencode(params)
browser = webdriver.Chrome(webDriver)
time.sleep(0.5)
browser.get(url)
html = browser.page_source
time.sleep(0.5)

    - 파라미터를 인코딩하여 url 주소에 합치고 webDriver를 구동하여 해당 url를 로드한다. 너무 빠른 처리는 구글에게 제한 당할 수 있기 때문에, 브라우저를 열고 url 로드 전에 한번, 로드 후에 한번 약간의 지연을 줬다.

 

3. Page Down

### get number of image for a page

soup_temp = BeautifulSoup(html,'html.parser')
img4page = len(soup_temp.findAll("img"))

### page down 

elem = browser.find_element_by_tag_name("body")
imgCnt =0
while imgCnt < size*10:
    elem.send_keys(Keys.PAGE_DOWN)
    rnd = random.random()
    print(imgCnt)
    time.sleep(rnd)
    imgCnt+=img4page

   - 현재 기본 페이지의 html 코드에서 img 태그를 모두 찾아 그 수를 세는 것으로 한 페이지 당 이미지의 개수를 변수로 저장하였다. imgCnt가 미리 정의해둔 size만큼 커질 때까지 페이지를 내린다.

 

4. html 가공, src 추출

html = browser.page_source
soup = BeautifulSoup(html,'html.parser')
img = soup.findAll("img")

browser.find_elements_by_tag_name('img')

fileNum=0
srcURL=[]

for line in img:
   if str(line).find('data-src') != -1 and str(line).find('http')<100:  
      print(fileNum, " : ", line['data-src'])  
      srcURL.append(line['data-src'])
      fileNum+=1

   - 브라우저의 html 코드를 읽고, img 태그의 data-src가 있는 line만 걷어 리스트에 추가한다. fileNum 변수로 이미지의 개수를 센다.

   

   *** line에 data-src가 먼저 있는지 확인하고 line['data-src']를 처리해야한다. 

 

5. 폴더 생성, 파일 저장

### make folder and save picture in that directory

saveDir = folder+searchItem

try:
    if not(os.path.isdir(saveDir)):
        os.makedirs(os.path.join(saveDir))
except OSError as e:
    if e.errno != errno.EEXIST:
        print("Failed to create directory!!!!!")
        raise

for i,src in zip(range(fileNum),srcURL):
    urllib.request.urlretrieve(src, saveDir+"/"+str(i)+".jpg")
    print(i,"saved")

   - 폴더의 존재 여부를 확인하고, 폴더를 생성 후, 파일을 저장한다. 

 

   *** urllib.request.urlretrieve는 폴더를 생성하지 못하는 것 같다. 폴더를 생성하고 그 위치를 지정해줘야 한다. 

 

result

 

- 한 500개 정도의 문 사진을 저장해보았다.

 

 

- 사실 이미 더 좋고 안정적인 모듈이 있어서 직접 데이터 뽑을 때는 사용하지 않을 것 같지만, 연습용으로는 간단하게 재밌었다.

 

https://github.com/hardikvasa/google-images-download 

 

hardikvasa/google-images-download

Python Script to download hundreds of images from 'Google Images'. It is a ready-to-run code! - hardikvasa/google-images-download

github.com

google image.txt
0.00MB

Comments