【问题标题】:JSON response from API request seems to be invalid in Python requests, but OK in Browser来自 API 请求的 JSON 响应在 Python 请求中似乎无效,但在浏览器中可以
【发布时间】:2020-01-19 12:40:01
【问题描述】:

我正在尝试从 API 读取响应,但每当我尝试访问 JSON 元素时,都会收到如下错误:

...
...
    print(parsed_data['result']['listing']['whisper'])
TypeError: list indices must be integers or slices, not str

我当前的代码如下:

import json
import requests
from bs4 import BeautifulSoup   

item_data_api = "https://www.pathofexile.com/api/trade/fetch/e6c3075c2bea510e868dd9568930c74cfd7d926e2dc74dd12b1119ecb565b3ff"
r = requests.get(item_data_api)

if r.status_code == 200:
    print(r.encoding)
    parsed_data = r.json()
    print(parsed_data)
    print(parsed_data['result']['listing']['whisper'])

如果我从 print 中获取输出并验证 https://jsonlint.com/ 上的 JSON,则它无效:

Error: Parse error on line 1:
[{  'id': 'e6c3075c2bea5
---^
Expecting 'STRING', '}', got 'undefined'

但是,如果我在浏览器中执行调用,响应是有效的。

我在这里缺少什么?有人可以提供有关如何使输出有效的提示吗?我已经尝试过json.loads(r.text),但也没有用。

【问题讨论】:

  • parsed_dataPython,而不是 JSON;它已经被解析了。如果 JSON 错误,r.json() 将失败。但正如您所见,parsed_data = [...] - 根元素是 list,而不是字典。您需要根据元素的实际类型访问元素

标签: python json web-scraping


【解决方案1】:

在这种情况下,问题是您返回的数据不是您期望的格式。

这一行:

print(parsed_data['result']['listing']['whisper'])

假设你得到的字典看起来像:

result = {
    "results": { 
        "listing": {
            "whisper": ...}}}

这不是返回的,更像是:

result = {
    "results": [
        {"listing": ... }
        {"listing": ... }]}

因此 results 实际上是返回一个字典列表,这就是您收到错误的原因 - 您无法使用字符串索引到列表中。

如果我运行您的代码并取出第一个结果字典,我不会收到您的错误:

print(parsed_data['result'][0]['listing']['whisper'])

【讨论】:

    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2016-09-26
    • 2012-07-10
    相关资源
    最近更新 更多