TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type s

直接上代码

import urllib.request
import urllib.parse
def request():
    #定义 HTTP的头部
    headers = {'User-Agent':'Mozilla/5.0','x-my-header':'my value'}
    req = urllib.request.Request('http://blog.kamidox.com',headers = headers)
    s = urllib.request.urlopen(req)
    print(s.read(100))
    print(req.headers)
    s.close()    
def request_post_debug():
    #post
    data = {'username':'kamidox','password':'xxxxxxx'}
    headers = {'User-Agent':'Mozilla/5.0'}  
    req = urllib.request.Request('http://www.douban.com',data  = urllib.parse.urlencode(data),headers = headers)    
    #创建一个打开器
    opener = urllib.request.build_opener(urllib.request.HTTPHandler(debuglevel = 1))
    s = opener.open(req)
    print(s.read(100))
    s.close()

if __name__=='__main__':
    request_post_debug()

看了好久没看出错误,最后无意间在网上发现答案,分享给大家,

Request('http://www.douban.com',data  = urllib.parse.urlencode(data).encode(encoding='UTF8'),headers = headers) 

大家对照一下找不同就解决了 哈哈。

你可能感兴趣的:(python)