コード:
#!/usr/bin/env python
#coding: utf-8
userid="**************@gmail.com"
passwd="*******"
import sys, re, cgi, urllib, urllib.request, urllib.error, http.cookiejar, xml.dom.minidom, time, urllib.parse
import simplejson as json
def getToken():
html = urllib.request.urlopen("http://www.nicovideo.jp/my/mylist").read()
for line in html.splitlines():
mo = re.match(r'^\s*NicoAPI\.token = "(?P<token>[\d\w-]+)";\s*',line)
if mo:
token = mo.group('token')
break
assert token
return token
def mylist_create(name):
cmdurl = "http://www.nicovideo.jp/api/mylistgroup/add"
q = {}
q['name'] = name.encode("utf-8")
q['description'] = ""
q['public'] = 0
q['default_sort'] = 0
q['icon_id'] = 0
q['token'] = token
cmdurl += "?" + urllib.parse.urlencode(q).encode("utf-8")
j = json.load( urllib.request.urlopen(cmdurl), encoding='utf-8')
return j['id']
def addvideo_tomylist(mid,smids):
for smid in smids:
cmdurl = "http://www.nicovideo.jp/api/mylist/add"
q = {}
q['group_id'] = mid
q['item_type'] = 0
q['item_id'] = smid
q['description'] = u""
q['token'] = token
cmdurl += "?" + urllib.parse.urlencode(q).encode("utf-8")
j = json.load( urllib.request.urlopen(cmdurl), encoding='utf-8')
time.sleep(0.5)
#ログイン
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
urllib.request.install_opener(opener)
urllib.request.urlopen("https://secure.nicovideo.jp/secure/login",
urllib.parse.urlencode( {"mail":userid, "password":passwd} ))
#トークン取得
token = getToken()
#マイリストの作成と動画の登録
mid = mylist_create(u"テストリスト")
addvideo_tomylist(mid, ["sm9","sm1097445", "sm1715919" ] )
エラー:
Traceback (most recent call last):
File "Nico3.py", line 47, in <module>
urllib.request.urlopen("https://secure.nicovideo.jp/secure/login", urllib.parse.urlencode( {"mail":userid, "password":passwd} ))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 162, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 463, in open
req = meth(req)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1170, in do_request_
raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
エラー2(追記)
Traceback (most recent call last):
File "Nico3.py", line 50, in <module>
token = getToken()
File "Nico3.py", line 11, in getToken
mo = re.match(r'^\s*NicoAPI\.token = "(?P<token>[\d\w-]+)";\s*',line)
File "/Users/NanjoHiroki/.virtualenvs/uec/lib/python3.5/re.py", line 163, in match
return _compile(pattern, flags).match(string)
TypeError: cannot use a string pattern on a bytes-like object
エラー3:
Traceback (most recent call last):
File "Nico3.py", line 50, in <module>
token = getToken()
File "Nico3.py", line 15, in getToken
assert token
UnboundLocalError: local variable 'token' referenced before assignment