Python2.7 如何检查响应是否为 json(如果是则解析)?

Python2.7 How do I check if a response is json (and parse it if it is)?

我有一个要解析的 '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 对象,该方法将抛出一个异常(如果没记错则为 ValueError),您可以捕获该异常。这是 Python 的 "ask for forgiveness" 工作方式。

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

import ast
ast.literal_eval(r.text)

内容类型在headers:

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