这是我的代码:
NSURL *url=[NSURL URLWithString:@"http://www.engadget.com"];
NSString *webPage=[[NSString alloc]initWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:nil];
在webPage字符串中,我得到了一个链接的html页面。在那个字符串中有很多标签和文字。我想只带一些没有任何标签的文本正文。
我想将该文本显示在我的UITextView中。我怎么能这样做?
答案 0 :(得分:1)
这是最好的答案,正是您所寻找的:
在webView委托方法中编写以下脚本。 (UIWebviewdidfinishLoading
)
NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
答案 1 :(得分:0)
从我的尝试来看,this做得最好。即使NSSCanner不是这方面的解决方案,如果html / xml形成良好,你应该没问题。
答案 2 :(得分:0)
更好的解决方案:
- (NSString *)flattenHTML:(NSString *)html {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
html = [html stringByReplacingOccurrencesOfString:
[ NSString stringWithFormat:@"%@>", text]
withString:@" "];
} // while //
return html;
}
参考:http://rudis.net/content/2009/01/21/flatten-html-content-ie-strip-tags-cocoaobjective-c