Python 웹크롤링 (Web Crawling) 03. 인스타그램 사진 크롤링 'chromedriver' executable needs to be in PATH 오류 해결법
공부용이라 과정이 틀릴수도 있고 위에서 쓴 구문을 아래에선 안 쓸 수도있음
참고는 프로그래머 김플 스튜디오
오늘은 인스타그램의 해시태그를 입력하면 사진을 크롤링 할 수 있는 프로그램을 만들거다 !
과정 (내 생각임)
1. html 불러오기
2. html 분석
3. 다운로드 !
네이버 크롤링이랑 비슷할것같다 !
우선 먼저 준비해야할 것이 있다 (BeautifulSoup4 를 설치했다는 가정하에)
구글에 chromedriver 을 검색후 맨 위에있는거에 들어가서 자신의 크롬 버전과 맞는 걸 다운받으면 된다
https://chromedriver.chromium.org/downloads
크롬 버전 확인하는 법 :
chrome://version/
이걸 검색창에 넣으면 버전이 나옵니다
그리고 다운로드 받은걸 파이썬 파일과 같은 폴더 안에 넣어줍니다
이후 터미널에
pip install selenium
설치를 해줍니다
그럼 준비는 완료 !
1. html 불러오기
import urllib.request
from urllib import parse
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import ssl
context = ssl._create_unverified_context()
search=input("input Hashtag ## : ")
url = "https://www.instagram.com/explore/tags/"
newUrl = url+parse.quote_plus(search)+'/'
이제 평소엔 html 을 불러들이기 위해 BeautifulSoup 을 사용하겠지만 오늘은 'webdriver' 을 사용한다
webdriver 사용하는 이유는
인스타의 코드가 전부 자바스크립트로 만들어져서 일반적인 BeautifulSoup 으로 안되고 webdriver을 사용해줘야한다
-webdriver 사용 모습
import urllib.request
from urllib import parse
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import ssl
context = ssl._create_unverified_context()
search=input("input Hashtag ## : ")
url = "https://www.instagram.com/explore/tags/"
newUrl = url+parse.quote_plus(search)+'/'
driver = webdriver.Chrome() #크롬을 이용
driver.get(newUrl)
html = driver.page_source #driver의 페이지 소스를 가져와서 html 에 담음
soup =BeautifulSoup(html)
driver 라는 변수를 만들어서 webdriver.Chrome() 에 넣는다 (나는 크롬을 썼기 때문)
그리고 newUrl 을 불러들입니다
html 변수안에 newUrl 이 들어있는 driver 의 페이지 소스를 가져오고
soup 으로 html 소스를 보기좋게 만들어주는 과정
에서 이 오류가 발생했다
'chromedriver' executable needs to be in PATH
path 관련 오류인것 같아터미널에서
1. sudo nano /etc/paths
2. 안에다가 /usr/local/bin 추가
3. 아까 chromedriver 있던 폴더로 cd 해서 mv chromedriver /usr/local/bin
했더니 해결이 되었다 !
2. html 분석
인스타그램에 #건후 를 검색한 모습이다 ! (너무 귀여움)
태그를 살펴보면 div class="v1Nh3 kIKUG _bz0w" 여기 부분이 저 이미지 하나를 가르키고 (이걸 A 라고 부르겠다)
a href="..." 안의 링크를 클릭하면
이런 글과 이미지를 불러올 수 있다
실질적인 이미지가 들어있는 곳은
div class="KL4Bh" 여기 아래의 img 태그안에 있다 (이건 B라고 부르겠음)
따라서 진짜 이미지 파일이 들어있는 곳은 img 안의 src 부분이다 (나머지는 그냥 사이즈인듯)
우리는 img 안의 src 부분을 다운로드 하면 된다는 것 !
3. 다운로드
import urllib.request
from urllib import parse
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import ssl
context = ssl._create_unverified_context()
search=input("input Hashtag ## : ")
url = "https://www.instagram.com/explore/tags/"
newUrl = url+parse.quote_plus(search)
driver = webdriver.Chrome() #크롬을 이용
driver.get(newUrl)
time.sleep(3) #여기서 3초를 기다린 다음에 아래꺼를 실행
html = driver.page_source #driver의 페이지 소스를 가져와서 html 에 담음
soup =BeautifulSoup(html)
insta = soup.select('.v1Nh3.kIKUG._bz0w') #이미지 파일이 들어있는 클래스(.으로 구분해준다)
n=1
for i in insta :
print('https://www.instagram.com'+i.a['href']) #누르면 나오는 주소
imgUrl = i.select_one('.KL4Bh').img['src'] #이미지가 들어있는 태그의 실질적 img
with urlopen(imgUrl) as f:
with open(search+str(n)+'.jpg','wb') as h :
img = f.read()
h.write(img)
n += 1
print(imgUrl)
print()
driver.close()
time.sleep(1)
print("End")
구체적으로 한줄씩 살펴보자
insta 변수에 soup.select("...") 이미지 파일이 들어있는 클래스를 넣어준다 (A)
클래스를 넣는거기 때문에 각 클래스를 . 로 구분해줘야함 !!
n은 파일명에 쓰일 것
for 문을 보면 A 아래의 a태그의 href 부분을 포함해 url 을 print 해준다
imgUrl 은 B 아래의 img 의 src 를 갖게된다 이게 이미지 파일임 (한개만 가져오니까 select_one)
with 문을 써서 이미지 파일을 열어주고
이름은 검색어 + n(넘버링) +.jpg 를 write,바이너리로 불러와준다
(경로를 바꾸고 싶으면 경로+이름,'wb')
사진을 읽어들인걸 img 에 읽어들이고
h.write() 를 이용해 쓰기를 한다
이후 n을 1증가
driver 를 닫아준다
(time.sleep 랑 print 는 그냥 내가 넣은거라 의미 x)
오늘은 자바스크립트로 만들어진 웹들을 처리하는 방법을 배웠다
selenium 을 쓰면 가능한데 단점은 시간이 좀 걸린다는거 정도 ?
이거 이용해서 다양하게 해봐야겠다