我目前正在使用 Instagram API 构建一个小型应用程序它为 GET 操作回复 JSON“对象”。为了获得响应,我目前正在使用 urllib2。
这是我目前正在参加的一门类(class)的作业的一部分,最大的挑战是我们不允许使用 JSON 库来快速解析和检索来自 instagram 响应的信息。我们被迫使用正则表达式库(且仅此)来正确解析信息。
instagram响应格式获取用户feed页面,例如,遵循this link所示结构.
老实说,我花了 3 个小时试图自己解决这个问题,也尝试在互联网上获取信息,但大多数回答的问题总是指出使用 JSON 库。
任何提示或建议都会派上用场。
此外,除了 urllib2(可能被认为是外部的),除了 python 2.7 提供的那些之外,我不允许使用任何其他外部库(更像是第 3 方库)。
提前致谢。
请您参考如下方法:
其实并没有那么复杂,当你执行 get 请求时,你会得到一堆代码,你只需要从中提取一些小部分,例如,如果你想解析来自用户的新闻提要,并得到图片及其说明:
query = "https://api.instagram.com/v1/users/"+profile_id+"/media/recent?access_token="+token
response = urlopen(query)
the_page = response.read()
feed = {}
feed['images'] = []
feed['captions'] = []
matchImage = re.findall(r'"standard_resolution":{"url":"(.*?)"', the_page)
matchCaption = re.findall(r'"caption":(.*?),(.*?),', the_page)
if len(matchImage) > 0:
for x in xrange(0,len(matchImage)):
image = matchImage[x].replace('\\','')
if matchCaption[x][0] == 'null':
feed['images'].append(image)
feed['captions'].append('No Caption')
else:
caption = re.search(r'"text":"(.*?)"', matchCaption[x][1])
caption = caption.group(1).replace('\\','')
feed['images'].append(image)
feed['captions'].append(caption)
