2009-05-04 34 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。