0

我正在加载整个 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
4

1 回答 1

0

好的,我终于想通了......如果有人像我一样愚蠢,我希望这会有所帮助:

所需要做的就是将 URL 加载到 webview 中,然后简单地执行一个简单的 javascript 查询,如下所示(在 webViewDidFinishLoad 中):

NSString *bread_text = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('entry breadtext')[0].innerHTML"];

获取知名课程中的所有内容。现在我需要弄清楚如何在不首先显示 webview 的情况下加载它,但这似乎比遍历 XML 结构容易得多:)

于 2012-12-07T16:19:10.103 回答