본문 바로가기
2. Data Science Basics/Python

Reddit에서 코인뉴스 API로 크롤링하기

by Mojito 2021. 12. 28.

 

import requests
import pandas as pd
# Token 구하기
auth = requests.auth.HTTPBasicAuth(CLIENT_ID, SECRET_KEY)
data = {
    'grant_type' : 'password', 
    'username' : username,
    'password' : password
}

headers = {'User-AGent': 'MyAPI/0.0.1'}
res = requests.post('https://www.reddit.com/api/v1/access_token',
                    auth = auth,
                    data = data,
                    headers = headers)​

 

TOKEN = res.json()['access_token']
headers = {**headers, **{'Authorization': f'bearer {TOKEN}'}}
# API 에서 cryptocurrency 에 대해 hot 한 주제를 100개 가져와서 reddit.csv로 저장

res = requests.get('https://oauth.reddit.com/r/cryptocurrency/hot', headers = headers,
                    params={'limit':'100'})
                    
df = pd.DataFrame()

for post in res.json()['data']['children']:
    df = df.append({
        'title' : post['data']['title'],
        'num_comments' : post['data']['num_comments'],
        'url' : post['data']['url'],
        'ups' : post['data']['ups'],
        'downs' : post['data']['downs'],
        'score' : post['data']['score'],
    }, ignore_index=True)

df.sort_values(by=['num_comments'], inplace=True, ascending=False)
df.to_csv("../temp/reddit1.csv", encoding='utf-8-sig')
print(res.json())
반응형

댓글