熟悉 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 *)sender didFinishLoadForFrame:(WebFrame *)frame
回调你应该能够访问 DOM。另外,当负载完成时,设置done
标记为“是”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)