2009-05-04 60 views
2

可能有人谁是熟悉的webkit请解释或点我在正确的方向,为什么下面的代码不工作访问DOM的Webkit目标C

我想要做的是加载一个页面,有webkit解析它并简单地打印标题。

这里是我已经有了:

#include <iostream> 
#include <WebKit/WebKit.h> 

using namespace std; 

/* 
Seek Help 
*/ 
int main (int argc, char * const argv[]) {  
    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; 

    WebFrame * mainFrame; 
    WebView * view = [[WebView alloc] initWithFrame: NSMakeRect (0,0,640,480)]; 

    mainFrame = [view mainFrame]; 
    NSString * url = @"http://test.com"; 
    [[view mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]]; 

    NSString * data = @"<html><head><title>testing</title></head><body>tester</body></html>"; 
    [[view mainFrame] loadHTMLString:data baseURL: nil]; 

    // NSString * urlString = [[NSString alloc] initWithUTF8String:"<html><head><title>Hello World</title></head><body><p>My first Web page.</p></body></html>"]; 

    //[[view mainFrame] loadHTMLString:urlString baseURL:nil];  

    NSString * outerHtml = [(DOMHTMLElement *)[[[view mainFrame] DOMDocument] documentElement] innerHTML]; 

    cout << "Html: " << [outerHtml UTF8String] << endl; 

    NSString * title = [view mainFrameTitle]; 

    cout << "title: " << [title UTF8String] << endl; 

    [autoreleasepool release]; 

    return 0; 
} 

输出是HTML和标题都是空白

感谢您阅读

回答

4

它不工作,因为WebKit的依赖RunLoop加载内容,即使它只是静态内容。

您应该添加一个标准的运行循环,例如:

while (!done) { 
    pool = [[NSAutoreleasePool alloc] init]; 
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode 
          beforeDate:[NSDate distantPast]]; 
    [pool release]; 
} 

,并创建你设置为WebFrameLoadDelegate(webView.frameLoadDelegate = thatObject)的自定义类,并在- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame回调,你应该能够访问DOM。同样当负载完成时,将done标志设置为YES。

+0

frameLoadDelegate? – 2009-06-30 16:47:45

0

如果您只是想解析HTML,为什么不使用NSXMLDocument而不是WebView。我相信它的initWithContentsOfURL初始化程序阻塞,直到加载url。如果这不起作用,请为该URL创建一个NSURLRequest,然后使用[NSURLConnection sendSynchronousRequest:..]加载它,然后将其提供给NSXMLDocument。