gpt4 book ai didi

ios - 从网页获取图片URL

转载 作者:行者123 更新时间:2023-11-28 19:48:42 25 4
gpt4 key购买 nike

我正在尝试从该网站获取图像,但我遇到了困难。我所需要的只是图像的 URL,当我打印 URL 时,我得到了回复。这是 URL,我试图在中间看到主图像,http://theoldrussuanbum.vsco.co/media/555722fde555153e3e8b4591

我一直在尝试以下代码,但没有成功。

NSURL *URL = [NSURL URLWithString:_urlTextField.text];

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:URL completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *contentType = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields];


contentType = headers[@"Content-Type"];
}
HTMLDocument *document = [HTMLDocument documentWithData:data
contentTypeHeader:contentType];

HTMLElement *element = [document firstNodeMatchingSelector:@"img"];

NSString *urlString = element.attributes[@"src"];

NSLog(@"URL: %@", urlString);

}] resume];

有人能帮忙吗?

最佳答案

可以先用正则表达式
找到正则表达式的开头:@"twitter:image\"\\s+content=\""
然后
使用正则表达式提取 URL:@"[^>]+"

您可以在 ICU 用户指南中找到有关正则表达式语法的信息:Regular Expressions .

示例代码:

NSString *urlString = @"http://theoldrussuanbum.vsco.co/media/555722fde555153e3e8b4591";
NSURL *URL = [NSURL URLWithString:urlString];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *sessionTask;
sessionTask = [session dataTaskWithURL:URL completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {

NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange preambleRange = [html rangeOfString:@"twitter:image\"\\s+content=\"" options:NSRegularExpressionSearch];
if (preambleRange.location != NSNotFound) {
NSString *htmlOffset = [html substringFromIndex:preambleRange.location + preambleRange.length];
NSRange imgUrlRange = [htmlOffset rangeOfString:@"[^>]+" options:NSRegularExpressionSearch];
if (imgUrlRange.location != NSNotFound) {
NSString *imgURLString = [htmlOffset substringWithRange:imgUrlRange];
NSLog(@"URL: %@", imgURLString);
}
}

}];
[sessionTask resume];

输出:

URL: http://image.vsco.co/1/548c6a64020e11517164/555722fde555153e3e8b4591/600x800/vsco_051615.jpg"

当然,生产代码必须处理此示例代码无法处理的所有错误。

关于ios - 从网页获取图片URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30470155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com