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

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

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

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

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

넘나 쉽고 편리한 파이썬!

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

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 연결하기  (2) 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

Warning: Declaration of selective_Walker::start_el(&$output, $item, $depth = 0, $args = Array) should be compatible with Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0)

워드프레스에서 해당 에러가 발생했다.

이 문장을

function start_el(&$output, $item, $depth=0, $args=array()) {

 

이렇게 수정해주면 끝!

function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

 

WAMP를 이용하여 서버에 올라가 있는 프로젝트를 로컬에서 실행시켜보자.

1. 프로젝트 다운로드

2. WAMP 다운로드

www.wampsercer.com/en/

3. DB 가져오기

라이브 DB 를 export하여 'phpmyadmin' 에 import

경로

4. DB 값 바꾸기

UPDATE wp_options SET option_value = replace(option_value, 'http://www.yoursitename.com', 'http://localhost');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.yoursitename.com', 'http://localhost');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.yoursitename.com','http://localhost');

 

5. httpd-vhost.conf 설정 바꾸기

경로 : WAMP - Apache - httpd-vhosts.conf

<VirtualHost localhost:80>
  DocumentRoot "Local Project Path"
  ServerAdmin localhost
  <Directory "Local Project Path">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
  </Directory>
</VirtualHost>

 

 

6. wp-config.php 값 바꾸기

define('DB_NAME', 'DB name');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', '');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

 

끝!

+ Recent posts