2019년 1월 15일 화요일

Capstone Design :: python-twitter을 이용하여 트윗 수집하기

이번 글에서는 데이터 구조와 함수 사용한 것을 작성하겠습니다.

앞서 작성했던 글을 보면 첫 번째로 할 일이 트윗 수집, 웹 크롤링 이라고 할 수 있습니다.

우선 api를 사용하기 전에 함수의 매개변수(parameter)를 알아야 되고 함수의 리턴값이

어떻게 반환되는지도 알아야 합니다.

자세한 사항은 twitter developer 사이트에 가면 확인할 수 있습니다.

GetSearch

우선 GetSearch를 이용하여 아무거나 검색한 후 데이터 타입을 확인해 보겠습니다.

results = api.GetSearch(raw_query = 'q="python twitter api"')
print(type(results))

결과는 <class 'list'> 입니다.

그럼 list들은 어떠한 타입으로 이루어졌나 확인해 보겠습니다.

print(type(results[0]))

결과는<class 'twitter.models.Status'> 입니다.

데이터를 출력해 보겠습니다

for res in results:
    print(res)
    print("\n")

{"created_at": "Tue Jan 15 06:56:16 +0000 2019", "hashtags": [], "id":

1085068131372912646, "id_str": "1085068131372912646", "lang": "ko", "source": "<a

href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>", "text":

"\ud2b8\uc704\ud130 \uace0\uae09\uac80\uc0c9\uacfc\npython twitter api /

GetSearch() \ud568\uc218 \uc0ac\uc6a9\uc5d0 \ub300\ud55c

\ud3ec\uc2a4\ud305\nhttps://t.co/nfwMnVNtlA", "urls": [{"expanded_url":

"https://fouaaa.blogspot.com/2019/01/twitter-search.html", "url":

"https://t.co/nfwMnVNtlA"}], "user": {"created_at": "Thu Oct 11 13:41:47 +0000 2018",

"default_profile": true, "default_profile_image": true, "description": "Capstone Design

\uc9c4\ud589\uc911\n\ud2b8\uc704\ud130 \ubd84\uc11d\uc5d0

\uad00\uc2ec\uc788\uc73c\uba74

\ub4e4\ub824\uc8fc\uc138\uc694\ud83d\ude00\ud83d\ude00\n#twitter

api\n#python-twitter", "followers_count": 1, "geo_enabled": true, "id":

1050380947378515968, "id_str": "1050380947378515968", "lang": "ko", "name": "Tester",

"profile_background_color": "F5F8FA", "profile_image_url":

"http://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png",

"profile_image_url_https":

"https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png",

"profile_link_color": "1DA1F2", "profile_sidebar_border_color": "C0DEED",

"profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333",

"profile_use_background_image": true, "screen_name": "3LTYxHTRnlMRHX8",

"statuses_count": 6, "url": "https://t.co/U0lxs3fyMk"}, "user_mentions": []}

출력 결과는 너무 길어서 잘랐습니다.

위 출력 결과를 보면 created_at, hashtags, id .. 등의 정보를 가지고 있는 걸 볼 수

있습니다. 중간에 제 아이디도 보이네요.

그런데 글들이 알수없는 문자로 깨져서 나오는걸 볼 수 있습니다.

이는 결과값을 아크키코드로 가져와서 한글이 정상적으로 출력 되지 않는 것이므로

유니코드로 변환시켜서 볼 수 있습니다.

print(u"아스키코드") 식으로 출력할 수 있습니다.


저는 GetSearch함수를 이용해 가져온 모든 값이 필요하지 않습니다.

class Status(TwitterModel):    """A class representing the Status structure used by the twitter API.    """    def __init__(self, **kwargs):        self.param_defaults = {            'contributors': None, 'coordinates': None, 'created_at': None, 'current_user_retweet': None, 'favorite_count': None,             'favorited': None, 'full_text': None, 'geo': None, 'hashtags': None,  'id': None, 'id_str': None,            'in_reply_to_screen_name': None, 'in_reply_to_status_id': None,  'in_reply_to_user_id': None, 'lang': None,            'location': None, 'media': None,  'place': None,  'possibly_sensitive': None,  'quoted_status': None, 'quoted_status_id': None,             'quoted_status_id_str': None,  'retweet_count': None,  'retweeted': None,  'retweeted_status': None,  'scopes': None,  'source': None,             'text': None,  'truncated': None, 'urls': None,  'user': None, 'user_mentions': None,            'withheld_copyright': None, 'withheld_in_countries': None, 'withheld_scope': None,        }

이중에서 저는 created_at, text, user만을 이용할 것입니다.

for res in results:
    print(res.created_at, res.text, res.user)
    print("\n")

이렇게 원하는 정보만 가져올 수 있고 user 정보 중에서도 원하는 정보만 가져올 수

있습니다. user 정보는 twitter developer 사이트에서 확인할 수 있습니다.

너무 길어서 여기서는 언급하지 않겠습니다.

import datetime

nowtime = datetime.datetime.now()
since = nowtime - datetime.timedelta(days=10)
until = since + datetime.timedelta(days=1)

datetime을 이용하여 현재 날짜를 구하고

현재 날짜부터 10일 전 날짜, 그 전날짜를 구합니다.


while(since < datetime.datetime.now()):
    product = '"갤럭시 s9"'    results = api.GetSearch(term = product, until = until.strftime("%Y-%m-%d"), since = since.strftime("%Y-%m-%d"), count=100, lang='ko', result_type ='mixed')

#friends_count 팔로잉 수#followers_count 팔로워 수    for res in results:
        if(res.user.friends_count > 10 and res.user.friends_count < 300 and res.user.followers_count > 10 and res.user.friends_count - res.user.followers_count < 50 and res.user.followers_count - res.user.friends_count < 200):
            print(res.id,res.user.screen_name, res.user.friends_count, res.user.followers_count, res.created_at, res.hashtags,res.text)
            print("\n")

    since = since + datetime.timedelta(days=1)
    until = until + datetime.timedelta(days=1)

검색이 가능한 10일 전 날짜부터 현재 날짜까지 while을 통하여 검색을 진행했습니다.

if의 조건문은 광고나 가계정들을 걸러내기 위해 조건문을 설정해 주었습니다.

가계정은 follower가 별로 없고 있다고 해도 follower와 following를 비교했을 때

following수가 더 많을 것 이라고 생각했고 실제로 그런 경우가 조금 더 많이 발견돼서

이렇게 조건을 주었습니다.

하지만 가장 큰 난관에 봉착했습니다. 약 일주일 전에 게시된 트윗밖에 검색할 수 없다는 것

입니다. 데이터를 수집하고 분석하여 점수화를 시키기에는 턱없이 부족한 양입니다.

혹시나 하는 생각으로 tweepy도 사용해 봤습니다.

하지만 역시 트위터에서 제공하는 토큰값을 받아서 사용하는 api기 때문에 7일간의

트윗밖에 검색할 수 없습니다.

그 이전의 트윗을 수집하는 방법을 더 공부해야겠습니다.

댓글 없음:

댓글 쓰기