Python的“海峡”对象有没有属性“读”(Python 'str' object

2019-11-02 14:23发布

Python的3.3.2进口JSON和urllib.request里

JSON

[{"link":"www.google.com","orderid":"100000222"},
{"link":"www.google.com","orderid":"100000222"},
{"link":"www.google.com","orderid":"100000222"}]

打印(response.info())

Date: Sun, 20 Oct 2013 07:06:51 GMT
Server: Apache
X-Powered-By: PHP/5.4.12
Content-Length: 145
Connection: close
Content-Type: application/json

代码

url = "http://www.Link.com"
    request = urllib.request.Request(url)
    request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
    request.add_header('Content-Type','application/json')
    response = urllib.request.urlopen(request)

    decodedRes = response.read().decode('utf-8')
    json_object = json.load(decodedRes)

以下是我的代码错误

Traceback (most recent call last):
  File "C:\Users\Jonathan\Desktop\python.py", line 57, in <module>
    checkLink()
  File "C:\Users\Jonathan\Desktop\python.py", line 50, in checkLink
    json_object = json.load(decodedRes)
  File "C:\Python33\lib\json\__init__.py", line 271, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> .

任何想法如何,我可以解决这个问题?

Answer 1:

使用json.loads代替json.load

json.loads(decodedRes)
  • json.load接受类文件对象。

>>> import json
>>> json.load('{"a": 1}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 286, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> json.loads('{"a": 1}')
{u'a': 1}

另外,您可以通过响应对象json.load

## decodedRes = response.read().decode('utf-8')
json_object = json.load(response)


Answer 2:

尝试更换json.load()json.loads() 前者需要一个文件流。这是你正在运行到属性错误的原因。



Answer 3:

这很简单,你只需要导入美丽的汤以另一种方式。 现在要导入为

from beautifulSoup import BeautifulSoup

将其更改为

from bs4 import BeautifulSoup


文章来源: Python 'str' object has no attribute 'read'