The jonki

呼ばれて飛び出てじょじょじょじょーんき

bottonZZ: Twitterにニコニコのマイリスランキング100を投稿

またまた新作。
ニコニコのマイリストのランキングから30分に1回、ランダムな動画を投稿。
はてぶの人気エントリとりだすbottonZとプログラムはほぼ同じ。
BeautifulSoupを使ったHTMLレベルでのパースだしね。
違うのはログインしなきゃ目的URLが見れないとこね。
けどまぁ、ググったら30秒で解決したw

今まで30分に一回投稿、ってのをスリープ関数使ったダサいプログラム書いてたけど、今回はcrontabコマンドつかってプログラムの実行をスケジューリングしてみた。
crontabの使い方がイマイチ分からん!って人はコメントアウトしたところ使って今までどおりスリープ関数使えます。

今こんな感じに投稿してます


・cronNiko (cronの設定ファイル)


*/30 * * * * /home/hoge/python/runNiko.sh


・runNiko.sh

#!/bin/sh
python /home/hoge/python/nikoniko.py


・nikoniko.py

#!/usr/bin/python
#-*- coding: utf-8 -*-

#@author Junki OHMURA
#@date 2009/02/13

import re
import cookielib
import urllib
import urllib2
from BeautifulSoup import BeautifulSoup
import twitter
import random
import time

#参考:http://d.hatena.ne.jp/y_yanbe/20070827/1188160390#
def login(username, password):
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
req = urllib2.Request('http://www.nicovideo.jp/ranking/mylist/daily/all');
account = {"mail": username, "password": password}
req.add_data(urllib.urlencode(account.items()))
return opener.open(req).read()
# return opener


def getNiko(_soup):
_niko = []
for mylist, rank, video in zip(
_soup.findAll('a', href=re.compile('^openlist')), #openlistで始まるリンク
_soup.findAll('span',style=re.compile('^font')), #fontで始まるspan
_soup.findAll(attrs={'class': 'video'}) ): #class="video"
twt = ''
twt += '[' + mylist.find('strong').string + ' mylists: ' + rank.string + '位] '
twt += video.string
twt += ' http://www.nicovideo.jp/' + video['href']
# print '[' + mylist.find('strong').string + ' mylists: ' + rank.string + '位]'
# print video.string
# print ' http://www.nicovideo.jp/' + video['href']
_niko.append(twt)

return _niko

username = 'login-addr@com'
password = 'password'
html = login(username, password)
soup = BeautifulSoup(html)
niko = getNiko(soup)

html = login(username, password)
soup = BeautifulSoup(html)
niko = getNiko(soup)
randNiko = random.randint(0,len(niko)-1)

print niko[randNiko]
tapi = twitter.Api(username='bottonzz', password='botton')
status = tapi.PostUpdate(niko[randNiko])

"""
while(2>1):
html = login(username, password)
soup = BeautifulSoup(html)
niko = getNiko(soup)
randNiko = random.randint(0,len(niko)-1)

print niko[randNiko]
tapi = twitter.Api(username='bottonzz', password='botton')
status = tapi.PostUpdate(niko[randNiko])
time.sleep(1800) #単位は秒、1800秒=30分
"""