everyone.
I'm trying to get all image urls of the current page in UIWebView.
So, here is my code.
- (void)webViewDidFinishLoad:(UIWebView*)webView {
NSString *firstImageUrl = [self.webView stringByEvaluatingJavaScriptFromString:@"var images = document.getElementsByTagName('img');images[0].src.toString();"];
NSString *imageUrls = [self.webView stringByEvaluatingJavaScriptFromString:@"var images= document.getElementsByTagName('img');var imageUrls = "";for(var i = 0; i < images.length; i++){var image = images[i];imageUrls += image.src;imageUrls += \\’,\\’;}imageUrls.toString();"];
NSLog(@"firstUrl : %@", firstImageUrl);
NSLog(@"images : %@",imageUrls);
}
1st NSLog returns correct image's src, but 2nd NSLog returns nothing.
2013-01-25 00:51:23.253 WebDemo[3416:907] firstUrl: https://www.paypalobjects.com/en_US/i/scr/pixel.gif
2013-01-25 00:51:23.254 WebDemo[3416:907] images :
I don't know why. Please help me...
Thanks.
Perrohunter pointed out one
NSRegularExpression
solution, which is great. If you don't want to enumerate the array of matches, you can use the block-basedenumerateMatchesInString
method, too:I've also updated the regex pattern to deal with the following issues:
img
tag and thesrc
attribute;src
attribute and before the>
;img
tag (the.
captures everything except newline character);src
attribute value can be quoted with'
as well as"
; andsrc
and the=
as well as between the=
and the subsequent value.I freely recognize that reading regex patterns is painful for the uninitiated, and perhaps other solutions might make more sense (the JSON suggestion by Joris, using scanners, etc.). But if you wanted to use regex, the above pattern might cover a few more permutations of the
img
tag, andenumerateMatchesInString
might be ever so slightly more efficient thanmatchesInString
.You could achieve this running a regex on the loaded webview html source code
This is a pretty basic regex that matches anything inside a tag, it would need more details if your images have more attributes such as class or id's
I don't like regular expressions, so here's my answer without them.
The javascript indented for clarification:
You'll notice I return a JSON string here. To read this back in Objective-C:
With given html, you can use SwiftSoup library. Using Swift 3