我可以访问一个.webarchive文件。到目前为止,我已经设法从该文件创建了一个the存档(使用PyObjC)。我希望修改DOM树中的一些元素,并将修改后的数据写出来。
我想我需要访问一些根DOM树( WebArchive是一个网页,没有链接),给定一个webarchive。
有谁知道如何在Cocoa中做到这一点吗?谢谢
发布于 2011-03-07 14:41:51
可能的解决方案(尚未检查)
from Foundation import *
import objc
import WebKit
from WebKit import *
d=NSData.dataWithContentsOfFile_("/tmp/x.webarchive")
ws=WebArchive.alloc().initWithData_(d)
wv=WebView.alloc().initWithFrame_frameName_groupName_(((100, 100),(100,100)), "foo",None)
mf=wv.mainFrame()
mf.loadArchive_(ws)发布于 2011-03-08 10:05:08
将WebArchive加载到WebView中的代码看起来是正确的(我对PyObjC不是很熟悉)。使用WebKit应用编程接口(documentation)中的方法修改DOM非常容易。棘手的是,一旦修改了DOM,并且想要将修改写回WebArchive。简单地保存一个新的WebArchive是行不通的,因为这不会保留您所做的修改,所以您需要编写新的源代码。下面是一些可以做到这一点的代码(这里的WebView是webview,原始的WevArchive位于archivePath,修改后的版本也将在那里编写):
//Get the string representation of the current DOM tree
NSString *sourceString = [(DOMHTMLElement *)[[[webview mainFrame] DOMDocument] documentElement] outerHTML];
NSData *sourceData = [sourceString dataUsingEncoding:NSUTF8StringEncoding];
//Load the archive from disk to a dictionary (it's a plist)
NSMutableDictionary *archive = [[NSMutableDictionary alloc] initWithContentsOfURL:[NSURL fileURLWithPath:archivePath]];
//Modify the main HTML
[(NSMutableDictionary *)[archive objectForKey:@"WebMainResource"] setObject:sourceData forKey:@"WebResourceData"];
//Write the plist back out
NSData *data = [NSPropertyListSerialization dataFromPropertyList:archive format:NSPropertyListBinaryFormat_v1_0 errorDescription:nil];
[data writeToURL:[NSURL fileURLWithPath:ArchivePath] atomically:YES];这是一个小技巧,因为它依赖于归档格式的内部结构,但我认为你可以很有把握地假设它不会有很大的变化。
https://stackoverflow.com/questions/5216556
复制相似问题