@markdown
# python tweepy 사용한 트위터 크롤링(crawling)
<br/>
## 1. 트위터 API 앱 생성하기
____
- 트위터 `App Management` 페이지에 로그인 후 `Twitter App`을 생성한다.
- [https://apps.twitter.com/](https://apps.twitter.com/)

- `Name`, `Description`, `Website`를 채우고 App을 생성한다.(Website 주소는 facebook이나 블로그 주소 넣어도 됨)
## 2. API key, Access Token
____
- `App Management`에서 생성한 `Twitter App`을 클릭해 `Keys and Access Tokens` 탭으로 이동한다.
- python 코드에서 이 4가지 `Consumer Key(API Key)`, `Consumer Secret(API Secret)`, `Access Token`, `Access Token Secret` 키를 사용하므로 복사해둔다.
## 3. Key, Access Token 추가
____
- `tweepy` python 패키지를 사용해 크롤링한다.
- Terminal에서 `tweepy` 패키지를 설치한다.
```
> pip install --upgrade pip
> pip install tweepy
```
- 트위터 앱 콘솔에서 만든 자신의 Key와 and Access Token을 넣어준다.
<pre><code class="python" style="font-size:15px"># tweepy 패키지 import
import tweepy
# API 인증요청
consumer_key = "Your API Key"
consumer_secret = "Your API Secret Key"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# access 토큰 요청
access_token = "Your Access Token"
access_token_secret = "Your Access Token Secret"
auth.set_access_token(access_token, access_token_secret)
# twitter API 생성
api = tweepy.API(auth)
</code></pre>
<br/>
## 4. tweepy.Cursor 사용
____
- 다양한 검색 조건을 줄 수 있는 함수로 검색 키워드, 검색 위치 및 반경, 검색 날짜 등으로 트윗을 검색할 수 있다.
- API 문서 - [https://dev.twitter.com/rest/reference/get/search/tweets](https://dev.twitter.com/rest/reference/get/search/tweets)
<pre><code class="python" style="font-size:15px">location = "%s,%s,%s" % ("35.95", "128.25", "1000km") # 검색기준(대한민국 중심) 좌표, 반지름
keyword = "파이썬 OR 아는형님" # OR 로 검색어 묶어줌, 검색어 5개(반드시 OR 대문자로) # api 생성
wfile = open(os.getcwd()+"/twitter.txt", mode='w') # 쓰기 모드
# twitter 검색 cursor 선언
cursor = tweepy.Cursor(api.search,
q=keyword,
since='2015-01-01', # 2015-01-01 이후에 작성된 트윗들로 가져옴
count=100, # 페이지당 반환할 트위터 수 최대 100
geocode=location, # 검색 반경 조건
include_entities=True)
</code></pre>
<br/>
## 전체 소스코드
____
<pre><code class="python" style="font-size:15px"># -*- coding: utf-8 -*-
import tweepy
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
consumer_key = "Your API Key"
consumer_secret = "Your API Secret Key"
access_token = "Your Access Token"
access_token_secret = "Your Access Token Secret"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
location = "%s,%s,%s" % ("35.95", "128.25", "1000km") # 검색기준(대한민국 중심) 좌표, 반지름
keyword = "파이썬 OR 아는형님" # OR 로 검색어 묶어줌, 검색어 5개(반드시 OR 대문자로)
wfile = open(os.getcwd()+"/twitter.txt", mode='w') # 텍스트 파일로 출력(쓰기모드)
# twitter 검색 cursor 선언
cursor = tweepy.Cursor(api.search,
q=keyword,
since='2015-01-01', # 2015-01-01 이후에 작성된 트윗들로 가져옴
count=100, # 페이지당 반환할 트위터 수 최대 100
geocode=location,
include_entities=True)
for i, tweet in enumerate(cursor.items()):
print("{}: {}".format(i, tweet.text))
wfile.write(tweet.text + '\n')
wfile.close()
</code></pre>
<br/>
- 검색어로 파이썬과 아는형님으로 검색한 트윗들 결과화면

'Bot 기술노트' 카테고리의 다른 글
웹페이지 게시물 업데이트 알람 봇 만들기(2) (0) | 2019.07.14 |
---|---|
웹페이지 게시물 업데이트 알람 봇 만들기(1) (12) | 2019.07.11 |
BotFramework Rest API로 사용하기 (0) | 2017.08.30 |
BotFramework으로 간단한 챗봇 만들기 (0) | 2017.08.29 |