Python으로 구글 스프레드 시트에 연결하여 읽고 쓰는 방법입니다!!!

(정말 엄청난 삽질과 구글링 끝에.....엉엉)

1. 구글 API 만들기

1) https://console.developers.google.com 에 접속해서, 좌측의 라이브러리에서 API 검색 후 설정

- Google Sheets API, Google Drive API 두개 설정해야 합니다.

- 설치 후, 사용자 인증? 해야 합니다.(방금 해놓고 까먹은....)

2. 사용자 인증 정보 만들기

1) https://console.developers.google.com 에 접속해서, 좌측의 '사용자 인증 정보' 클릭 후, 계정 생성

2) JSON으로 생성하고, 여기서 다운받은 파일을 잘 간수하세요.

3. 구글 시트 만들기

1) 시트를 만든 후, 공유버튼을 클릭하여, 다운받은 json 파일에 있는 client_email 을 수정권한으로 초대

4. 코딩코딩

pip install gspread
pip install --upgrade oauth2client
pip install PyOpenSSL
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('C:\dev\My Project-sample.json', scope)

gc = gspread.authorize(credentials).open("Google Sheet Name")

wks = gc.get_worksheet(0)

gc.get_worksheet(-1)## integer position으로 접근
gc.worksheet('Sheet Name) ## sheet name으로 접근

wks.update_acell('D1', 'It's Work!')

# Select a range
cell_list = wks.range('A1:C7')

for cell in cell_list:
    cell.value = 'test'

# Update in batch
wks.update_cells(cell_list)

끝!

 

 

 

'Programming > Python' 카테고리의 다른 글

Python Mailchimp API 연동  (0) 2019.07.16
Python 웹페이지 크롤링 후 Slack으로 공유  (1) 2019.07.16
Phthon Pycharm으로 MySQL 연결하기  (1) 2019.07.16

회사에서 어떤 데이터를 가지고 놀아볼까 고민하다가 메일침프로 결정!

저희 회사에서는 메일침프로 메일링 마케팅을 하고 있어서,

이에 따른 결과를 가져와서 보여주면 좋지 않을까 생각했습니다.

아무래도 국내에서는 메일침프를 많이 사용하지도 않아서 그런지, 레퍼런스도 많이 없더라고요.

생각보다 더 쉽고 금방하니까 아래 참고하세용~ㅎㅎㅎ

넘나 쉽고 편리한 파이썬!

(나중에 슬랙으로 연결해서 주단위로 리포팅하도록 해볼게요!)

1. 프로젝트 만들기

2. mailchimp3 모듈 설치

3. 코드 작성!

from mailchimp3 import MailChimp

client = MailChimp(mc_api='API KEY', mc_user='USER')

list_reports = client.reports.all(get_all=False)

total_item = list_reports['total_items']
report = list_reports['reports'][0]

print('total_item: ', total_item)
print('campaign_title: ', report['campaign_title'])
print('opens_total: ', report['opens']['opens_total'])
print('clicks_total: ', report['clicks']['clicks_total'])
print('hard_bounces: ', report['bounces']['hard_bounces'])
print('soft_bounces: ', report['bounces']['soft_bounces'])

 

저는 Report가 필요해서 이렇게 사용했지만, 아래 API 문서 보시고 필요한 부분 작성해보세요~

https://developer.mailchimp.com/documentation/mailchimp/reference/reports/

회사에서 dialy로 data를 공유해달라는 오더가 떨어졌습니다.

근데 이 사이트는 한달 뒤에 리뉴얼 예정이라, 그냥 대충 데이터가 출력되는 페이지를 만들어서 슬랙에 복/붙 하는 형식으로 했는데.....

매일 하려니 이것도 여간 귀찮은게 아니더라고요

그래서 파이썬으로 자동 스케쥴러를 만들기로 했습니다.

스케쥴러는 사내 리눅스 서버를 이용해도 되지만, 어차피 한달뒤면 사장될 프로그램이라....

귀찮으니 그냥 로컬 컴퓨터(윈도우)로 진행!

그럼 이미 만들어 놓은 페이지를 파이썬으로 크롤링하여 Slack으로 공유해보겠습니다.

1. Slack Bot 만들기

https://ndb796.tistory.com/200

위의 포스팅에서 아주 자세히 나왔더라고요ㅎㅎㅎㅎ

주의할 점은 해당 슬랙 채널에서 꼭 'Add app' 을 해줘야 합니다.

2. 파이썬 프로그램 만들기

제가 만든 것을 대충 간추렸습니다.

# -*- coding: utf-8 -*-
from slacker import Slacker
import requests
from datetime import date, timedelta
import urllib.request
import io
from bs4 import BeautifulSoup

output = io.StringIO()
main_url = "http://yoursiteurl.com"
with urllib.request.urlopen(main_url) as response:
    html = response.read()

def get_total():
        soup = BeautifulSoup(html, 'html.parser')
        table = soup.select(".total_data tr")
        output = ""

        for index, tr in enumerate(table):
            output += tr.select('td')[0].text+"\n"
        return output

def main():
    yesterday = date.today() - timedelta(1)
    date_text = "** *" + yesterday.strftime("%y-%m-%d") + " 통계* **"

    html = get_total()
    print(html, file=output)

    out_text = output.getvalue()
    output.close()

    with requests.Session() as session:
        slack = Slacker('tockentockentockentockentockentocken', session=session)
        attachments_dict = dict()
        attachments_dict['pretext'] = date_text
        attachments_dict['text'] = out_text
        attachments_dict['mrkdwn_in'] = ["text", "text"]  # 마크다운을 적용시킬 인자들을 선택합니다.
        attachments = [attachments_dict]

        slack.chat.post_message(channel="#slack_channel", text=None, attachments=attachments, as_user=True)

if __name__ == '__main__':
    main()

3. 윈도우 스케쥴러 등록

1) 작업 스케쥴러 실행(윈도우키 > 예약 작업)

프로그램/스크립트 : C:\Users\Philip\SlckTest\Scripts\pythonw.exe

인수추가(옵션): C:\Users\Philip\PycharmProjects\SlckTest\slakc_test.py

매일 이상없이 실행이 되야하니, 등록을 마친 후에 조건을 수정!

끝! 쉽쥬?

그럼 지정된 시간이 슬랙으로 오는지 확인해봅시다.

* 파이썬으로 웹 크롤링 하는 포스팅은 다음에 기회가 된다면 올리겠습니다~^^

'Programming > Python' 카테고리의 다른 글

Python Google Sheet 읽기,쓰기  (0) 2019.07.18
Python Mailchimp API 연동  (0) 2019.07.16
Phthon Pycharm으로 MySQL 연결하기  (1) 2019.07.16

파이참을 이용하여 MySQL에 연결 해보자!

파이참으로는 클릭 몇번으로 PyMySQL을 설치할 수 있다.

1. 프로젝트 생성

1) 'Create New Project' 클릭

2) 프로젝트명 입력하고 'Create' 클릭

2. PyMySQL 설치

1) 'File - CloseProject' 한 후, 'Configure - Settings' 클릭

2) 'Project Interpreter - 프로젝트 선택 - + 아이콘' 클릭

3) 검색창에 'pymysql' 입력 후, 선택하여 'Install Package' 클릭

3. 파일 생성

1) 프로젝트 선택하여 파이썬 파일 생성

4. 코드 작성

1) 코드 작성 후, 실행하면 끝!

참 쉽쥬?

'Programming > Python' 카테고리의 다른 글

Python Google Sheet 읽기,쓰기  (0) 2019.07.18
Python Mailchimp API 연동  (0) 2019.07.16
Python 웹페이지 크롤링 후 Slack으로 공유  (1) 2019.07.16

+ Recent posts