Python 3使用urllib出现错误

3
无论何时我在Python 3中运行以下代码,都会出现语法错误invalid syntax。 我认为导致这种情况的原因是Python 3中的print具有不同的语法。
import sys
from urllib.request import urlopen
from urllib.request import Request
import json

request = Request(
    "https://gcm-http.googleapis.com/gcm/send",
    dataAsJSON,
    { "Authorization" : "key="+MY_API_KEY,
      "Content-type" : "application/json"
    }
)

print urlopen(request).read()

然而,当我将最后一行改成以下内容时:
result = urlopen(request).read()

我遇到了如下错误:
TypeError: POST数据应为bytes、bytes的可迭代对象或文件对象。不能为str类型。

Python 3 的 print 是一个函数,所以使用它时要加上括号 print()。尝试将你的字符串转换为 bytearray,可以使用以下代码:ba = urlopen(request).read().encode('latin1') - Chen A.
@Vinny 仍然是同样的错误。 - tony9099
1个回答

3
在创建request对象之前,将您的数据转换为字节字符串。
dataAsJSON = dataAsJSON.encode()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接