본문 바로가기
● 크롤링, 자동화/OpenAPI

조코딩AI.1 : 텍스트 및 이미지 크롤링하기. BeautifulSoup

by 0ver-grow 2020. 5. 19.
반응형

Q> selenium, BeautifulSoup의 차이점? 왜 동적인 네이버실검은 selenium으로만 되는가?

- BS :  HTML 및 XML 파일에서 데이터를 가져 오는 Python 라이브러리

 

Selenium으로 무적 크롤러 만들기 · GitBook

Selenium은 주로 웹앱을 테스트하는데 이용하는 프레임워크다. webdriver라는 API를 통해 운영체제에 설치된 Chrome등의 브라우저를 제어하게 된다. 브라우저를 직접 동작시킨다는 것은 JavaScript를 이용

beomi.github.io


 

[조코딩] 완성형 서비스 만들기 - 1

참고: 조코딩 - 완전 쉽게 파이썬으로 텍스트 및 이미지 크롤링하기 | 완성형 서비스 만들기 1강https://www.youtube.com/watch?v=ZTJjW7XuHIY&list=PLU9-uwewPMe2-vtJAgWB6SNhHcTjJDgEO파이썬을 활용해

velog.io

 


1. 다음사이트 추천 검색어(텍스트) 크롤링하기

from bs4 import BeautifulSoup
from urllib.request import urlopen

response = urlopen('https://www.daum.net/')
soup = BeautifulSoup(response, 'html.parser')
for anchor in soup.select("a.link_favorsch"):
    print(anchor.get_text())

위에서 soup.select에서 사용한 select의 사용방법

 

Beautiful Soup Documentation — Beautiful Soup 4.9.0 documentation

Non-pretty printing If you just want a string, with no fancy formatting, you can call unicode() or str() on a BeautifulSoup object, or a Tag within it: str(soup) # ' I linked to example.com ' unicode(soup.a) # u' I linked to example.com ' The str() functio

www.crummy.com

추출할 때, 순위를 매겨서 출력해보자

from bs4 import BeautifulSoup
from urllib.request import urlopen

response = urlopen('https://www.daum.net/')
soup = BeautifulSoup(response, 'html.parser')
i = 1
for anchor in soup.select("a.link_favorsch"):
    print(str(i) + "위 "+ anchor.get_text())
    i += 1

2. 출력한 것을 메모장에 써보자

검색어 : 언어 + 행위

검색어 : python write text file

https://wikidocs.net/26

이를 참고해서 코딩을 해보자

f = open("text.txt", "w")
f.close()
from bs4 import BeautifulSoup
from urllib.request import urlopen

response = urlopen('https://www.daum.net/')
soup = BeautifulSoup(response, 'html.parser')
i = 1
f = open("text.txt","w")
for anchor in soup.select("a.link_favorsch"):
    data = str(i) + "위 : " +anchor.get_text() + "\n"
    i += 1
    f.write(data)
f.close()

3. 이미지를 크롤링하자 (방법3가지 알려줌)

앞에서 실검의 태그의 공통점을 찾았듯이, 특정 검색어와 함께 나타난 이미지의 공통된 태그들을 찾자 
그런데 왠만하면 라이브러리가 만들어져 있다. 해당 기능을 가진 라이브러리를 찾아쓰자

검색어 : python google image search and download

1. Google image crawler

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

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

 

google_images_download

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

pypi.org

이를 사용하기 위해 다음을 입력하여 설치한다. : pip install google_images_download

만약 주피터 노트북이라면 제일 앞에 !를 쓰고 한 칸 띄운뒤 입력하면 설치된다.

이제 예제를 보며 사용법을 익히자

여기에 들어가서 코드샘플을 복사하자

이 코드를 복사한 뒤, 새파일을 만들어서 복사한 코드를 넣자.

from google_images_download import google_images_download   #importing the library

response = google_images_download.googleimagesdownload()   #class instantiation

arguments = {"keywords":"Polar bears,baloons,Beaches","limit":20,"print_urls":True}   #creating list of arguments
paths = response.download(arguments)   #passing the arguments to the function
print(paths)   #printing absolute paths of the downloaded images

실행가능하나 폴더만 만들어지고 파일은 다운이 안된다.
알고보니 구글 검색 방식이 바뀌어 알려준 대로 하면 안된다.


2. 네이버 코드

여기 내용을 참고해서 진행해보자

우선 img라는 폴더를 코드파일과 동일한 위치에 생성 후 하단 코드 실행

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='
plusUrl = input('검색어를 입력하세요 : ')
# 한글 검색 자동 변환
url = baseUrl + quote_plus(plusUrl)
html = urlopen(url)
soup = bs(html, "html.parser")
img = soup.find_all(class_='_img')

n = 1
for i in img:
    imgUrl = i['data-source']
    with urlopen(imgUrl) as f:
        # img폴더 안에 저장
        with open('./img/' + plusUrl + str(n)+'.jpg','wb') as h: # w - write b - binary
            img = f.read()
            h.write(img)
    n += 1
print('다운로드 완료')
# os 모듈을 임포트시켜 폴더를 검색어 이름으로 생성하게 만들고 그 경로로 들어가서 추가할 수 있게 만들었습니다.

from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
from urllib.parse import quote_plus
import os

baseUrl = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='
plusUrl = input('검색어를 입력하세요 : ')
# 한글 검색 자동 변환
url = baseUrl + quote_plus(plusUrl)
html = urlopen(url)
soup = bs(html, "html.parser")
img = soup.find_all(class_='_img')

#폴더를 검색어로 생성
dir_path = './img/'
dir_name = plusUrl
os.mkdir(dir_path + "/" + dir_name + "/")
path = dir_path + '/' + dir_name + '/'
n = 1
for i in img:
imgUrl = i['data-source']
with urlopen(imgUrl) as f:
with open(path +plusUrl+str(n)+'.jpg','wb') as h: # w - write b - binary
img = f.read()
h.write(img)
n += 1
print('다운로드 완료')

3. 깃허브 코드

https://0ver-grow.tistory.com/646

 

반응형