如何从Objective C中的HTML获取有效的图像数据

时间:2012-06-09 17:32:24

标签: objective-c image parsing

这是我试图检索图像的HTML部分。

div class="image">
              <a href="http://www.web.com/EN/105/News/10228/"><img src="/images/cache/360x295/crop/images%7Ccms-image-000007796.jpg" width="360" height="295" alt=" (photo: )" /></a>
                         </div>

我可以单独获取“href”和“img src”值,但它们都不是让我到达图像的链接。有效链接为http://www.web.com加上img src值。我想把字符串:http://www.web.com附加到img src但是无法弄清楚如何做到这一点并且不确定这是正确的方法。所以,我想要的是http://www.web.com/images/cache/360x295/crop/images%7Ccms-image-000007796.jpg

这是我解析HTML数据的代码:

-(void) fethchData

{
    NSError *error = nil;
    NSURL *url=[[NSURL alloc] initWithString:@"http://www.web.com/"];
    NSString *strin=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

    HTMLParser *parser = [[HTMLParser alloc] initWithString:strin error:&error];

    if (error) {
        NSLog(@"Error: %@", error);
        return;
    }

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];
            HTMLNode *imNode = [imgNode firstChild];
             NSURL* imageURL = [NSURL URLWithString:[imNode getAttributeNamed:@"src"] relativeToURL:url];
        NSLog(@"%@", imageURL);

        } 
    }



}

这是输出:/images/cache/360x295/crop/images%7Ccms-image-000007653.jpg -- http://www.web.ge/

我需要先看http://www.web.ge/,然后再看其余的。

1 个答案:

答案 0 :(得分:0)

使用:

NSURL* imageURL = [NSURL URLWithString:[imNode getAttributeNamed:@"src"] relativeToURL:theURLFromWhichYouDownloadedThisHTML];

更新:如果您认为必须拥有绝对网址对象,则可以按照上述内容执行以下操作:

imageURL = [imageURL absoluteURL];