2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【python/Instagram】Instagram Like-bot を作る。logを保存する。

Last updated at Posted at 2021-01-22

InstaPy を使い、自動like-botを作ります。

Package                            Version
---------------------------------- ----------------------
instapy                            0.6.13
pandas                             1.0.5
schedule                           0.6.0

 
 
InstaPy関数でログイン情報を設定しセッションを作ります。
like_by_tags関数で検索したいタグ(list可)を指定し、amountでライクする数を指定します。
最後にend関数でセッションを終了します。

# job
from instapy import InstaPy
session = InstaPy(username="user_name", password="password", headless_browser=True)
session.login()
session.like_by_tags([tag], amount=10)
session.end()

 
 
 
 

InstaPyでセッションを開始すると自動でホームフォルダにInstapyフォルダが作成されその中に.logが作成されます。今回はその.logから文字を抽出し、.csvにまとめていきます。
logging モジュールを使って、もっと効率的にlogを抽出したかったのですが、logging初心者なので挫折しました。もっといいやり方あれば教えてください。

# makelog
import pandas as pd
import re

url_id = []
keep_phrases = ['Image from: b\'', '  Link: b\'']
        
with open('/path/to/.log/', 'r') as f:
   f = f.readlines()
        
for lines in f:
   for phrase in keep_phrases:
      if phrase in lines:
          url_id.append(lines)
          break
date = list()
user_id = list()
link = list()
df = pd.DataFrame() 
        
        
for line in url_id:
   if bool(re.search(r'Link: b\'',line)):
      a = re.search(r'Link: b\'',line)
      link.append(line[a.span()[1]:len(line)-2])
      date.append(line[6:25])
   elif bool(re.search(r'Image from: b\'',line)):
      a = re.search(r'Image from: b\'',line)
      user_id.append(line[a.span()[1]:len(line)-2])
        
df = pd.DataFrame(list(zip(date, user_id, link)), columns =['date', 'user_id', 'link'])
df.to_csv('/path/to/.csv', header = True, index=False)

 

 

以上の2つの処理をschedule モジュールで時間を指定して走らせます。

import schedule

schedule.every().day.at("15:20").do(job)
schedule.every().day.at("21:29").do(job)
schedule.every().day.at("00:00").do(makelog) 

        

  

この様にまとめてくれます。(URLはポストのURLです)
Screen Shot 2021-01-22 at 9.09.54.png

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?