簡體   English   中英

Python 'str' 對象沒有屬性 'read'

[英]Python 'str' object has no attribute 'read'

Python 3.3.2 導入 json & urllib.request

傑森

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

打印(響應。信息())

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'
>>> .

知道如何解決這個問題嗎?

使用json.loads而不是json.load

json.loads(decodedRes)

>>> 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)

嘗試用json.load()替換json.loads() 前者需要一個文件流,這就是您遇到屬性錯誤的原因。

以下代碼將 json 文件加載到文檔中。 文檔將具有 dict 類型的值。

file_name = "my_file.json"
with open(file_name, 'r') as f:
    document =  json.loads(f.read())

很簡單,你只需要用另一種方式導入美麗的湯。 現在您正在導入為

from beautifulSoup import BeautifulSoup

將其更改為

from bs4 import BeautifulSoup

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM