TypeError:POST数据应该是字节或可迭代的字节。它不能是str类型

时间:2016-05-12 00:43:26

标签: api python-3.x urllib

我的代码。

#!/usr/bin/env python
#coding: utf-8
userid="NicoNicoCreate@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)

#Login
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}) ).encode("utf-8")
#GetToken
token = getToken()
#MakeMylist&AddMylist
mid = mylist_create(u"Testlist")
addvideo_tomylist(mid, ["sm9","sm1097445", "sm1715919"  ] )

MyError。

Traceback (most recent call last):
  File "Nico3.py", line 48, in <module>
    urllib.parse.urlencode( {"mail":userid, "password":passwd}) ).encode("utf-8")
  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.

我尝试过编码,但没有帮助。 我是日本学术界的学生。 据我所知,它无法解决。 我知道这个类似的问题,TypeError:POST数据应该是字节或可迭代的字节。它不可能是str,但是对于答案来说太新了太多了。

1 个答案:

答案 0 :(得分:0)

你paren在错误的地方,所以你实际上并没有编码:

 .urlencode({"mail":userid, "password":passwd}).encode("utf-8")) # <- move inside