繁体   English   中英

在Objective-C中从HTML解析图片

[英]Parse picture from HTML in Objective-C

我正在尝试从此html数据中检索图像:

<div class="image">
 <a href="http://www.website.com/en/105/News/10217/">
   <img src="/images/cache/105x110/crop/images%7Ccms-image-000005554.gif" 
        width="105" height="110" alt="kollsge (photo: author)" />
 </a>
</div>

这是我的代码:

HTMLNode *bodyNode = [parser body];

NSArray *imageNodes = [bodyNode findChildTags:@"div"];

for (HTMLNode *imageNode in imageNodes) {
    if ([[imageNode getAttributeNamed:@"class"] isEqualToString:@"image"]) {
        NSLog(@"%@", [imageNode getAttributeNamed:@"img src"]);
    } 
}

帮助将不胜感激。

我通过以下代码解决了它:

 for (HTMLNode *imageNode in imageNodes) {
        if ([[imageNode getAttributeNamed:@"class"] isEqualToString:@"image"]) {
            HTMLNode *aNode = [imageNode firstChild];
            HTMLNode *imgNode = [aNode nextSibling];
            HTMLNode *imNode = [imgNode firstChild];
            NSLog(@"%@", [imNode getAttributeNamed:@"src"]);
        } 
    }

您没有正确穿过树。 您正在尝试在div上找到一个名为img src的属性。 看起来像这样:

<div class="image" img src="whatever">

一方面,那不是有效的HTML,但更重要的问题是您想看孩子们 您要查找的内容嵌套在div中,而不是属性中。 由于您的div只有一个孩子,因此快速浏览一下注释中提供的项目会使我相信以下方法会起作用:

HTMLNode *bodyNode = [parser body];

NSArray *imageNodes = [bodyNode findChildTags:@"div"];

for (HTMLNode *imageNode in imageNodes) {
    if ([[imageNode getAttributeNamed:@"class"] isEqualToString:@"image"]) {
        HTMLNode *aNode = [imageNode firstChild];
        HTMLNode *imgNode = [aNode nextSibling];
        NSLog(@"%@", [imgNode getAttributeNamed:@"src"]);
    } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM