티스토리 뷰

파이썬을 이용해서 Instagram의 해쉬태그 갯수를 읽어와보자.

글은 의식의 흐름에따라 작성한다.

 

일단 기본적으로 사용할 놈들

1. requests

2. beautiful soup4

따라서 이놈들의 설치를 위해

pip install beautifulsoup4
pip install requests

를 하자

그리고 가장 기본적으로 웹페이지의 태그를 긁어와보자!

import requests
from bs4 import BeautifulSoup

def get_html(url):
_html = ""
resp = requests.get(url)
if resp.status_code == 200:
_html = resp.text
return _html


url = "https://www.instagram.com/explore/tags/f2f/"
html = get_html(url)

soup = BeautifulSoup(html, 'html.parser')
soup.find("span",{"class": "g47SY "})

여기서 "g47SY "는 해쉬태그 갯수가 나오는 span의 class 명이다. 맙소사 안된다. 정확히는

위의 코드를 통해 가져온 html 코드와, 실제 page에서 보여지는 html 코드가 다르다.

 

이유가 무엇일까?

https://stackoverflow.com/questions/18130499/how-to-scrape-instagram-with-beautifulsoup 에서 찾을 수 있었다.

instagram 페이지를 잘 살펴보면, javascript들이 page를 자동 생성하는 부분이 있는데, 이러한 부분은 웹 브라우져가 이 페이지를 로드하고 난 이후에 생성되는 것이기 때문에, python의 requests를 통해서 단지 읽어오기만 하면 code generate가 되기 전의 코드가 로드되기 때문이다. 즉, Selenium 같은 녀석을 이용해서 page를 rendor한 이후의 html를 가져와야 쓸모가 있어진다.

 

이제 Selenium에서 Firfox driver를 통해서 페이지를 로드하고 긁어오려고했더니.. 이제는 또 아래와 같은 에러가 발생한다.

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

Ie() 의 driver를 통해서 로드하려고 하면 아래와 같은 에러가 발생한다.

selenium.common.exceptions.WebDriverException: Message: 'IEDriverServer.exe' executable needs to be in PATH. Please download from http://selenium-release.storage.googleapis.com/index.html and read up at https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver

Chrome() 이면 아래와 같은 에러가 발생

selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

아.. geckodriver 또는 IEDriverServer 등이 path에 등록돼야 하는거구만.

다운 받자! 나는 chromedriver 를 쓰기로 결정

https://sites.google.com/a/chromium.org/chromedriver/downloads

에서 chromedriver를 다운 받은 후 아래 코드를 실행하자

from bs4 import BeautifulSoup
import selenium.webdriver as webdriver

url = "https://www.instagram.com/explore/tags/jmt/"
driver = webdriver.Chrome()
driver.get(url)

soup = BeautifulSoup(driver.page_source, "html.parser")
count_tag = soup.find("span",{"class": "g47SY "})

print(count_tag)

그러면 아래와 같이 TAG 갯수가 정상적으로 읽힌다.

DevTools listening on ws://127.0.0.1:1329/devtools/browser/3774c9d6-64dd-4e67-a04f-0c59fbe5258c

KLIB_SelfTest return : KLR_OK
<span class="g47SY ">137,422</span>

근데 실행 한번 할 때마다 Chrome 프로세스가 하나씩 실행된다...

그리고 위 동작 실행 중, Chrome 프로세스를 강제로 꺼버리면 정상적으로 파싱 수행도 안된다.

이건 어떻게 해결해야할까?

다음편에 계속!

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함