熟悉webkit的人是否可以向我解释或指出正确的方向,为什么下面的代码不起作用

我要做的是加载一个页面,让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,标题是空白

感谢您阅读

有帮助吗?

解决方案

它不起作用,因为WebKit依赖于RunLoop来加载内容,即使它只是静态内容。

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

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

创建一个自定义类,设置为WebFrameLoadDelegate( webView.frameLoadDelegate = thatObject ),并在 - (void)webView:(WebView *)发送者didFinishLoadForFrame中:( WebFrame * )frame 回调你应该能够访问DOM。此外,当加载完成时,将 done 标志设置为YES。

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top