【问题标题】:Python2.7 How do I check if a response is json (and parse it if it is)?Python2.7如何检查响应是否为json(如果是则解析)?
【发布时间】:2017-03-22 03:06:54
【问题描述】:

我有一个我想解析的“requests.models.Response”对象。在响应上调用 response.json() 会生成一个 'unicode' 对象。

主要 - 如何检查响应是否为 json?

其次 - 我可以用 bs4 解析一个 json 'unicode' 对象吗?

我的代码如下:

import requests

post_hdrs = { 
    'type': 'regulated',
    'url': 'node/17'
}

r = requests.post(
    url='https://www.gfsc.gg/fetch-records-for-companies-table',
    data=post_hdrs,
)

json_data = r.json()

【问题讨论】:

    标签: json python-2.7 unicode python-requests bs4


    【解决方案1】:

    内容类型在标题中:

    >>> r.headers['Content-Type']
    'application/json'
    

    得到json数据后,用BeautifulSoup解析。示例:

    import requests
    from bs4 import BeautifulSoup
    
    post_hdrs = { 
        'type': 'regulated',
        'url': 'node/17'
    }
    
    r = requests.post(
        url='https://www.gfsc.gg/fetch-records-for-companies-table',
        data=post_hdrs,
    )
    
    print r.headers['Content-Type']
    print
    data = r.json()
    soup = BeautifulSoup(data)
    for c in soup.findAll('td',attrs={'class':'Company Name'}):
        print c.text
    

    输出:

    application/json
    
    2Mi Financial Services Limited
    71FS Insurance Company Limited
    7L Capital Partners Emerging Europe L.P.
    7L Equity Partners (EE) Limited
       :    :    :
    

    【讨论】:

    • 谢谢,这正是我想要的。
    • @Astrophe 奇怪的是它是一个返回 HTML 的 json 响应。有一个不应该需要的间接层,但这是服务器的问题。感谢您提供一个工作示例。
    • 感谢您澄清响应返回 HTML。我的印象是 json 响应将是字典中的键和值 - 这就是我问这个问题的原因。
    【解决方案2】:

    如果它不是一个有效的 json 对象,该方法将抛出一个异常(如果内存服务,则为 ValueError),您可以捕获该异常。这是 Python 的“请求宽恕”的工作方式。

    至于处理 unicode,这应该可以解决问题:

    import ast
    ast.literal_eval(r.text)
    

    【讨论】:

    • 谢谢 我不熟悉 ast。我得到了没有错误的良好输出,但我不确定如何解析它 - 我不想使用正则表达式然后发现我可以将它传递给例如BS4。 ast 对解析 unicode 有用吗?
    • 您的意思是 r.json() 返回您的 unicode 或正确的 json?如果你在 'r.text' 中得到的是包含 json 对象的 unicode,那么我发布的代码将把它变成一个正确的 json。
    • 使用您发布的代码获得“正确的 json”后,我可以从中获取 bs4 文档吗?
    • 什么是“bs4 文档”?使用 bs4,您可以从 HTML 和 XML 文件中提取数据。在这种情况下,您已经有了半结构(字典)的东西。
    • json 是名称-值对的集合,可以翻译成字典。因此,如果 unicode 字符串将具有 json 结构,那么您可以在输出中期望字典。这是我的代码中的一个示例:github.com/tracek/gee_asset_manager/blob/master/geebam/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    相关资源
    最近更新 更多