Bookmarks.plist文件是Safari存储书签的方式。我如何计算所有URLStrings?
我可以通过以下方式获取书签文件:
BOOKMARKS_PLIST = '~/Library/Safari/Bookmarks.plist
将其转换为二进制文本:
converted = subprocess.call(['plutil', '-convert', 'xml1', bookmarksFileCopy])
例如,使用以下命令访问单个条目
'print plist ['Children'] [5] ['Children'] [1] ['Children'] [2]'
似乎我应该使用递归来沿着'树的叶子'走下去,但我无法在python中获得正确的语法。你可以说,我是初学者。
编辑: 谢谢你。虽然你的解决方案给出了我在下面描述的错误,但我确实得到了这个:
import plistlib
import subprocess
import os
def countURLStrings(plistDict):
childURLCounts = 0
if 'Children' in plistDict.keys():
for child in plistDict['Children']:
childURLCounts += countURLStrings(child)
if 'URLString' in plistDict.keys():
childURLCounts += 1
print plistDict.URLString
return childURLCounts
BOOKMARKS_PLIST = '/Users/me/Desktop/Safari-20150403175048/Bookmarks.plist'
converted = subprocess.call(['plutil', '-convert', 'xml1', BOOKMARKS_PLIST])
pl = plistlib.readPlist(BOOKMARKS_PLIST)
ct = countURLStrings(pl)
print ct
作为奖励,这个迭代版本比我尝试过的递归更快,而且失败了。
答案 0 :(得分:2)
第一个代码示例适用于Python 3.4.2。 load()方法在2.x中不可用,readPlist()方法遇到错误。使用Python 2.7.6成功测试了第二个代码示例。
BOOKMARKS_PLIST
示例代码Python 3.4.2
import plistlib
def countURLStrings(plistDict):
childURLCounts = 0
if 'Children' in plistDict.keys():
for child in plistDict['Children']:
childURLCounts += countURLStrings(child)
if 'URLString' in plistDict.keys():
childURLCounts += 1
return childURLCounts
BOOKMARKS_PLIST = '/Users/username/Library/Safari/Bookmarks.plist'
with open(BOOKMARKS_PLIST, 'rb') as fp:
pl = plistlib.load(fp)
countURLStrings(pl)
示例代码Python 2.7.6
import biplist
def countURLStrings(plistDict):
childURLCounts = 0
if 'Children' in plistDict.keys():
for child in plistDict['Children']:
childURLCounts += countURLStrings(child)
if 'URLString' in plistDict.keys():
childURLCounts += 1
return childURLCounts
BOOKMARKS_PLIST = '/Users/jaburaschi/Library/Safari/Bookmarks.plist'
with open(BOOKMARKS_PLIST, 'rb') as fp:
pl = biplist.readPlist(fp)
countURLStrings(pl)