Parse picture from HTML in Objective-C

2019-08-19 07:35发布

I am trying to retrieve the image from this html data:

<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>

This is my code:

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"]);
    } 
}

Help would be much appreciated.

I solved it by this code:

 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"]);
        } 
    }

1条回答
▲ chillily
2楼-- · 2019-08-19 07:45

You are not going through the tree correctly. You are attempting to find an attribute named img src on your div. That would look like this:

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

For one thing, that's not valid HTML, but the more important issue is that you want to be looking at the children. The thing you are looking for is nested inside the div, not an attribute. Since your div only has one child, a quick look at the project you provided in the comments leads me to believe that the following will work:

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"]);
    } 
}
查看更多
登录 后发表回答