MIXIに自動ログインして日記を更新するスクリプトを作成しました。
pymixi プロジェクト日本語トップページのコードを参考に丸々修正しました。
Blogや他の日記サービスをメインに使っており、mixiの日記を更新するのが面倒な人向け。
% $HOME/local/bin/python3 mixi.py
なお、Python3のインストール方法、Python2との差分に関しては「UnicodeEncodeError: に悩まされない。Python2.x から Python3.x への乗り換え」を参照してください。
ダウンロード先はmixi.pyです。(UTF-8形式で保存してください)
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import urllib.request, urllib.parse, urllib.error, re, time, warnings
from http.cookiejar import CookieJar
from urllib.request import HTTPCookieProcessor
############################
# Variables
############################
__version__ = '1.0'
MIXI_BASE_URL = "http://mixi.jp"
############################
# Classes
############################
class LoginFailure(Exception):
"""
ログインに失敗したときに送出される例外クラス
"""
class MIXI:
"""
MIXI クラス
"""
############################
# Internal Class Methods
############################
def __init__(self):
self.opener = urllib.request.build_opener(HTTPCookieProcessor(CookieJar()))
self.mixiid = None
def _post_diary(self, mixiid, title, body, submit="main", postkey=""):
params = urllib.parse.urlencode({"id": mixiid,
"diary_title": title,
"diary_body": body,
"submit": submit,
"post_key": postkey}).encode('utf-8')
try:
f = self.opener.open("%s/add_diary.pl" % MIXI_BASE_URL, params)
data = f.read().decode("euc-jp")
f.close()
return data
except:
print('url open error')
return None
def post_diary(self, title, body):
html = self._post_diary(self.mixiid, title, body)
if html == None:
return False
postkey = re.search('post_key" value="([^"]*)"', html).group(1)
html = self._post_diary(self.mixiid, title, body, "confirm", postkey)
if html == None:
return False
return True
############################
# Class Methods
############################
def login(self, email, passwd):
"""
mixi にログインするためのメソッド
BF_SESSION の中に mixiid が含まれているので Cookie 確認
""" params = urllib.parse.urlencode({"email": email, "password":passwd, "next_url":"home.pl"}).encode('utf-8') try : response = self.opener.open("%s/login.pl" % MIXI_BASE_URL, params) c = response.getheader("Set-Cookie") # 先頭から";"まで取り出す c = c[:c.find(";")] if c.find("session=") == 0: l = len("session=") self.mixiid = c[l:c.find("_", l)] response.close() except: print('url open error') raise LoginFailure # 別ファイルにする場合には必要 #from mixi import MIXI m = MIXI() m.login("メールアドレス", "パスワード") m.post_diary('python3から自動登録テスト'.encode('euc-jp'), '成功!'.encode('euc-jp'))
mixiの日記更新以外にもスクレイピング(ウェブサイトのデータを必要な部分だけ抽出して利用すること)として色々と活用できると思います。
このソースコードが行なっている事は、mixiに自動ログインした後に日記ページに指定した文字列をpostしています。