이미지 크롤링을 하기 위해서는 크롤링 혹은 스크레이핑에 필요한 패키지가 필요한데, beautifulsoup라는 것이 있다.
Anaconda에서 다음 코드를 입력하면 된다.
pip install beautifulsoup4
또한 검색 엔진 링크와 검색어 주소를 불러오기 위해 다음 모듈도 필요하다.
from urllib.request import urlopen
from urllib.parse import quote_plus
일반적으로 이미지 크롤링은 다음과같이 진행한다.
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
from urllib.parse import quote_plus
baseUrl = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='
query = "김종국"
url = baseUrl + quote_plus(query)
html = urlopen(url)
soup = bs(html, "html.parser")
img = soup.find_all(class_='_img')
cnt = 1
for i in img:
imgUrl = i['data-source']
print(imgUrl)
if cnt <= 20:
with urlopen(imgUrl) as f:
with open('./custom_dataset/train/jongkook/' + query + str(cnt) + '.jpg','wb') as h:
img = f.read()
h.write(img)
else:
with urlopen(imgUrl) as f:
with open('./custom_dataset/val/jongkook/' + query + str(cnt) + '.jpg','wb') as h:
img = f.read()
h.write(img)
if cnt == 30:
break
cnt += 1