MENU

python3解析JSONP数据

February 25, 2021 • 数据采集与数据分析(python)

Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
爬虫场景:发送请求后,返回JSONP,格式如: callbackFunction(["customername1","customername2"])
解决方法:使用正则表达式提取callbackFunction()以外的数据。
具体实施:

import json, re
JSONP = 'callbackFunction(["customername1","customername2"])'
j = json.loads(re.findall(r'^\w+\((.*)\)$',JSONP)[0])
print(type(j),j)

<class 'list'> ['customername1', 'customername2']

另外发现还有一种发放很有意思:(如果你肯定返回的jsonp是安全的情况下可以使用eval)

JSONP = 'callbackFunction(["customername1","customername2"])'

def callbackFunction(lists):
    print lists
eval(JSONP)

['customername1', 'customername2']
Last Modified: April 26, 2021