我正在加载整个 HTML 页面,并希望获取特定标签之间的所有内容。为此,我正在做:
articleXpathQueryString = @"//article/div[@class='entry breadtext']";
articleNodes = [articleParser searchWithXPathQuery:articleXpathQueryString];
item.content = [self recursiveHTMLIterator:articleNodes content:@""];
然后我有一个递归函数,它试图总结所有子节点的内容以及它们的 HTML 标签:
-(NSString*) recursiveHTMLIterator:(NSArray*)elementArray content:(NSString*)content {
for(TFHppleElement *element in elementArray) {
if(![element hasChildren]) {
//The element has no children
} else {
//The element has children
NSString *tmpStr = [[element firstChild] content];
if(tmpStr != nil) {
NSString *css = [element tagName];
content = [content stringByAppendingString:[self createOpenTag:css]];
content = [content stringByAppendingString:tmpStr];
content = [content stringByAppendingString:[self createCloseTag:css]];
}
NSString *missingStr = [[element firstTextChild] content];
if(![missingStr isEqualToString:tmpStr]) {
if(missingStr != nil) {
NSString *css= [element tagName];
content = [content stringByAppendingString:[self createOpenTag:css]];
content = [content stringByAppendingString:missingStr];
content = [content stringByAppendingString:[self createCloseTag:css]];
}
}
content = [self recursiveHTMLIterator:element.children content:content];
}
}
return content;
}
但是,即使结果在某种程度上令人满意,它也不会获取 img 标签,并且当 HTML 具有以下格式时会有点混乱:
<p>
<strong>-</strong>
This text is not parsed because it skips it after it acquires <strong>-</strong>, this is why I have the second if-statement which catches up "missing strings", but they are inserted in the wrong order
</p>
所以我的问题是,我应该继续尝试让递归方法正确解析,还是有更简单的方法来获取所需的 HTML(然后我在 web 视图中使用)。我正在寻找的是所有内容
<article> THIS </article>.
换句话说,我想用 TFHpple 做这样的事情(尽管代码不起作用):
articleXpathQueryString = @"//article/div[@class='entry breadtext']";
articleNodes = [articleParser searchWithXPathQuery:articleXpathQueryString];
item.content = [articleParser allContentAsString]; //I simply want everything in articleParser in a string format