지난 글 스프레드시트로 인스타그램 크롤링에 이어서
이번에는 파이썬을 활용해 인스타그램 팔로워 수 등을 크롤링 해보도록 하겠습니다. 물론 단순 크롤링이기 때문에~ 앱에서 보는 통계 수치에 비하면 비교적 간단한 정보만 수집하게 됩니다. 그럼에도 불구하고 다양한 계정의 팔로워 수치를 데일리로 찍으면 ‘데이터 셋’이 되겠죠?
![](https://ga4.kr/wp-content/uploads/2022/10/스크린샷-2022-10-18-오전-11.07.43-1024x172.png)
파이썬 활용. 인스타그램 크롤링
![](https://ga4.kr/wp-content/uploads/2022/10/스크린샷-2022-10-18-오후-1.27.39-1024x250.png)
실제로 인스타그램 크롤링을 제대로 하기 위해서는 로그인을 해야하기도 하고, user-agent며 건드려야 하는게 산더미 이지만, 이번 칼럼에서는 딱 필요한 기능만 설치해서 ‘라이브러리로’ 쉽게 쉽게 진행하도록 하겠습니다.
파이썬 좋다는게 뭐겠어요. 이런 라이브러리 언넝 가져다 효율 뽑아내는게 가능하기 때문이죠.
자 그럼 코드 부터 보겠습니다.
import instaloader
#인스타로더 사용 시작.
bot = instaloader.Instaloader()
#사용자 이름 정의 직접 기입해도 상관없습니다.
Username = input('Enter the Account Username: ')
#프로필을 정의합니다.
profile = instaloader.Profile.from_username(bot.context, Username)
print("Username: ", profile.username)
print("User ID: ", profile.userid)
print("Number of Posts: ", profile.mediacount)
print("Followers: ", profile.followers)
print("Followees: ", profile.followees)
15줄 코드로 username / id(number) / post 수 / 팔로워 수 / 팔로잉 수 를 받아옵니다. 로그인하지 않고 진행하는 스크립트이기 때문에 간단한 데이터만 받아옵니다.
이렇게 프린트된 데이터는 pandas 라이브러리르 활용하면 csv파일로
gspread 파이썬 라이브러리까지 활용한다면 똑같이 스프레드시트에 보낼 수 있습니다.
각각의 라이브러리 사용법은 다음 칼럼에서 상세히 다뤄 보도록 하고,
먼저 instaloader 사용을 위해 터미널에서
pip install instaloader
로 시작해줍니다. 설치를 기다리고 나면 위의 예시 스크립트를 붙여넣기해서 실행해주면 됩니다.
로그인 등을 연계해서 인스타로더 라이브러리를 활용하면 더 풍부한 데이터를 가져올 수 있는데요.
예를 들어 비활성 팔로워의 아이디 목록이나, graphql 등을 활용할 수 있습니다.
아래는 로그인시 사용한 graphql 구조입니다.
graphql_query
(query_hash, variables, referer=None, rhx_gis=None)
Do a GraphQL Query.Parameters
- query_hash (
str
) – Query identifying hash. - variables (
Dict
[str
,Any
]) – Variables for the Query. - referer (
Optional
[str
]) – HTTP Referer, or None. - rhx_gis (
Optional
[str
]) – ‘rhx_gis’ variable as somewhere returned by Instagram, needed to ‘sign’ request
Return type
The server’s response dictionary.graphql_node_list
(query_hash, query_variables, query_referer, edge_extractor, rhx_gis=None, first_data=None)
Retrieve a list of GraphQL nodes.
Deprecated since version 4.5: Use NodeIterator
instead, which provides more functionality.Return type
직접 로그인 정보를 넣는게 좀 그렇다면 세션 파일등을 저장해놨다가 호출하는 형식으로도 로그인 할 수 있기 때문에 활용가능성은 좀 더 다양할 것으로 보이네요.
graphql 문법에 대해 더 자세히 알아보시려면 페이스북에서 제공해주는 공식 문서를 확인하실 수 있습니다. 물론 썩 친절하지는 않지만요!
https://developers.facebook.com/docs/instagram-api/guides/insights