将Flickrapi响应对象保存为文本文件

时间:2014-10-13 01:47:04

标签: python flickr

import sys
import os
import urllib
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import tostring
import flickrapi

 api_key = '              '
 api_password = '           '
 photo_id='2124494179'
 flickr= flickrapi.FlickrAPI(api_key, api_password)
 #photos= flickr.photos_getinfo(photo_id='15295705890')
 #tree=ElementTree(flickr.photos_getinfo(photo_id))
 #image_id=open('photoIds.txt','r')
 #Image_data=open('imageinformation','w')
 #e=image_id.readlines(10)
 #f= [s.replace('\r\n', '') for s in e]
 #num_of_lines=len(f)
 #image_id.close()
 #i=0
#while i<269846:
# term=f[i]
 #try:
photoinfo=flickr.photos_getinfo(photo_id=photo_id)
photo_tree=ElementTree(photoinfo)
 #photo_tree.write('photo_tree')
 #i+=1
#photo=photo_tree.getroot()
#photodata=photo.getiterator()
#for elem in owner.getiterator():
#for elem in photo.getiterator():
for elem in photo_tree.getroot():
  farm=elem.attrib['farm']
  id=elem.attrib['id']
  server=elem.attrib['server']
 #title=photo_tree.find('title').txt
 #for child in elem.findall():
  # username=child.attrib['username']
  # location=child.attrib['location']
  #  user=elem.attrib['username']
print (farm)
print(id)
print(server)
#owner=photo_tree.findall('owner')
# print(username)
#filename="%s.txt"%(farm)
#f=open(filename,'w')
#f.write("%s"%farm)
#for elem in photo_tree.getiterator():
#for child in photo_tree.getiterator():
 #print (child.attrib)
 #owner=child.attrib['username']

我想从文件中读取数据并将其传递给flickrapi方法以获取图像&#39;使用python递归信息并将其作为文本保存在文件中:image id = .... user name = ... location = ... tags = ...依此类推。我可以使用.getroot()保存第一个元素的属性,但我试图获取其他元素的属性,但它返回错误。我想将属性保存到txt文件中,并从文件中读取图像ID,以便我可以在我正在使用的算法中使用这些数据。

1 个答案:

答案 0 :(得分:0)

因为我找到了解决问题的方法(我是初学者并且对python几乎一无所知),我们需要做的是迭代对象(因为它没有保存为xml文件) )使用标签名称如下:

photo_tree=ElementTree(photoinfo)
  for elem in photo_tree.getroot():
    uploaded=elem.attrib['dateuploaded']
    uploaded=datetime.datetime.fromtimestamp(float(uploaded)).strftime('%Y-%m-%d %H:%M:%S')
  for elem in photo_tree.getiterator(tag='dates'):
     taken_date=elem.attrib['taken']
     photo_info = open(head + 'filename/' + ('%d.txt') % (id),'a')
     photo_info.write(str(id)+'\t'+uploaded+'\t'+taken_date+'\t'+'\n')

它可以帮助那些寻求解决相同问题的人。或者可能有一种有效的方法来解决这个问题!!