Python urllib.request.urlopen:AttributeError:'bytes'对象没有属性'data' [英] Python urllib.request.urlopen: AttributeError: 'bytes' object has no attribute 'data'

查看:57
本文介绍了Python urllib.request.urlopen:AttributeError:'bytes'对象没有属性'data'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3并尝试连接到 dstk .我在 urllib 包中遇到错误.

I am using Python 3 and trying to connect to dstk. I am getting an error with urllib package.

我对SO进行了大量研究,找不到与该问题类似的东西.

I researched a lot on SO and could not find anything similar to this problem.

api_url = self.api_base+'/street2coordinates'
api_body = json.dumps(addresses)
#api_url=api_url.encode("utf-8")
#api_body=api_body.encode("utf-8")
print(type(api_url))
response_string = six.moves.urllib.request.urlopen(api_url, api_body).read()
response = json.loads(response_string)

如果我不对 api_url api_body 进行编码,则会得到以下信息:

If I do not encode the api_url and api_body I get the below:

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1247, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

但是,如果我尝试将它们编码为 utf-8 (取消注释行),则会出现以下错误:

However if I try and encode them to utf-8 (uncommenting the lines) then I get the below error:

 File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 514, in open
    req.data = data
AttributeError: 'bytes' object has no attribute 'data'

对我来说,这似乎是一个循环错误,我无法解决.我确实尝试过从SO方面考虑将其更改为 json.load 等,但是似乎没有任何效果.

This seems like a circular error for me and I am not able to resolve it. I did try make to solutions from SO regards to change it to json.load etc but nothing seems to work.

推荐答案

您正在对url和请求正文进行编码,但仅应对正文进行编码.

You are encoding both the url and the request body, but only the body should be encoded.

这应该有效:

api_url = self.api_base+'/street2coordinates'
api_body = json.dumps(addresses)
api_body=api_body.encode("utf-8")
response_string = six.moves.urllib.request.urlopen(api_url, api_body).read()
response = json.loads(response_string)

urlopen 的参数传递给另一个类以创建打开器,并且此类不知道是否已将其传递给url或 Request 实例.因此,它会检查"url"是否为字符串-如果"url"为字符串,则会创建一个 Request ,如果不是,则假定"url"为 Request >实例,并尝试设置其data属性,从而导致您看到的异常.

urlopen's arguments are passed to another class to create an opener, and this class does not know whether it has been passed a url or a Request instance. So it checks whether the "url" is a string - if the "url" is a string, it creates a Request, if not it assumes that "url" is a Request instance and tries to set its data attribute, causing the exception that you are seeing.

有问题的代码是这里.

这篇关于Python urllib.request.urlopen:AttributeError:'bytes'对象没有属性'data'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆